views:

1985

answers:

2

I am new with Linq and I would like to sort some data that are in the BindinList. Once I did my Linq query, I need to use back the BindingList collection to bind my data.

 var orderedList = //Here is linq query
 return (BindingList<MyObject>)orderedList;

This compile but fail in execution, what is the trick?

+5  A: 
new BindingList<MyObject>(orderedList.ToList())
leppie
Won't this break anybody who's subscribed to events on the list?
GWLlosa
@GWLlosa I believe it does
Dynami Le Savard
+1  A: 

That above only works when your linq query's select projection is explicitly typed as MyObject rather than select new which creates an instance of an anonymous object. In such cases the typeof(orderedList.ToList()) winds up as something akin to this: System.Collections.Generic.List<<>f__AnonymousType1>

ie: this should work:

var result = (from x in MyObjects
              where (wherePredicate( x ))
              select new MyObject {
                  Prop1 = x.Prop1,
                  Prop2 = x.Prop2
              }).ToList();
return new BindingList<MyObject>( result );

this will not:

var result = from x in db.MyObjects
       where(Predicate(x))
       select new {
       Prop1 = x.Prop1
       Prop2 = x.Prop2
      };
return new BindingList<MyObject>(result.ToList())
//creates the error: CS0030 "Cannot convert type 'AnonymousType#1' to 'MyObject'

In the second case they typeof(result) is: System.Collections.Generic.List<<>f__AnonymousType2> (the type params match the properties set in your select projection)

reference: http://blogs.msdn.com/swiss_dpe_team/archive/2008/01/25/using-your-own-defined-type-in-a-linq-query-expression.aspx