From: Paul on
Hello.

How can I send the result of a LINQ query to a BindingList?

I say not to do this:
<Customer> List lst = (from cust in select new dataContext.Customer
Customer (cust)). ToList <Customer> ();
foreach (Customer c in lst) lbindingListCust.Add (c);


Any ideas?
From: Peter Duniho on
Paul wrote:
> Hello.
>
> How can I send the result of a LINQ query to a BindingList?
>
> I say not to do this:
> <Customer> List lst = (from cust in select new dataContext.Customer
> Customer (cust)). ToList <Customer> ();

That doesn't even look to me like it would compile.

> foreach (Customer c in lst) lbindingListCust.Add (c);

If you've already converted the query result to a List<Customer> (i.e.
using ToList() as in your example), then this would be better:

BindingList<Customer> lbindingListCust = new BindingList<Customer>(lst);

But if you have no other reason to convert the query to a List<Customer>
instance, then creating the intermediate list is wasteful. Rather, you
might as well in fact explicitly execute the add in your own code:

// Assume original data source named "data"
IEnumerable<Customer> result = from cust in data select new
Customer(cust);
BindingList<Customer> lbindingListCust = new BindingList<Customer>()

foreach (Customer c in result)
{
lbindingListCust.Add(c);
}

Unfortunately, the BindingList<T> class does not support initializing
with a known capacity. If it did and if, as your example suggests, you
are not doing any filtering, just a projection, _and_ your original data
source has a known length, then you could improve the above a little by
pre-allocating the capacity of your output list to the correct size.

Note that if you anticipate that optimization to actually be important
(it's a relatively minor one, but you never know�it could be in some
cases), then you could write your own IBindingList implementation that
supported that.

That's a lot more work though; I would not bother with that approach
unless and until you have identified a genuine performance problem just
using the built-in BindingList<T> class.

Pete