Create an instance using a subset of properties from another instance with a safe type?

I have a data source to which I will not bind the X collection. X should contain a subset of certain properties of type Y (say, Y has the properties PropOne, PropTwo, PropThree) Of course, this can be done with an anonymous type:

void DoBind() { myGrid.DataSource = myCollectionOfYs.Select(y => new {y.PropOne, y.PropTwo}); } 

How can I change this method so that its caller can specify which properties to use in projection in a safe way? That is, something like strings:

 var expressions = new List<Expression<Func<Y, object>>>(); expressions.Add(y => y.PropOne); expressions.Add(y => y.PropTwo); DoBind(expressions); 
+4
source share
2 answers

Using your idea:

 void DoBind(Func<Y, object> func) { myGrid.DataSource = myCollectionOfYs.Select(funct); } 

And use like:

 DoBind(y => new {y.PropOne}); 
+2
source

Can you pass the select function to the DoBind method:

 public static void DoBind<T, TResult>(ICollection<T> collection, Func<T,TResult> selector) { DataSource = collection.Select(selector) } 

and then call it like this:

  DoBind(list, y => new { y.Prop1, y.Prop2 }); DoBind(list, y => new { y.Prop3, y.Prop2 }); 
+2
source

All Articles