c# - LINQ : Dynamic select -
consider have class :
public class data { public string field1 { get; set; } public string field2 { get; set; } public string field3 { get; set; } public string field4 { get; set; } public string field5 { get; set; } }
how dynamically select specify columns ? :
var list = new list<data>(); var result= list.select("field1,field2"); // how ?
is solution => dynamic linq ?
selected fields not known @ compile time. specified @ runtime
you can dynamically creating lambda pass select:
func<data,data> createnewstatement( string fields ) { // input parameter "o" var xparameter = expression.parameter( typeof( data ), "o" ); // new statement "new data()" var xnew = expression.new( typeof( data ) ); // create initializers var bindings = fields.split( ',' ).select( o => o.trim() ) .select( o => { // property "field1" var mi = typeof( data ).getproperty( o ); // original value "o.field1" var xoriginal = expression.property( xparameter, mi ); // set value "field1 = o.field1" return expression.bind( mi, xoriginal ); } ); // initialization "new data { field1 = o.field1, field2 = o.field2 }" var xinit = expression.memberinit( xnew, bindings ); // expression "o => new data { field1 = o.field1, field2 = o.field2 }" var lambda = expression.lambda<func<data,data>>( xinit, xparameter ); // compile func<data, data> return lambda.compile(); }
then can use this:
var result = list.select( createnewstatement( "field1, field2" ) );
Comments
Post a Comment