考虑我们有这个课程:
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; } }
如何动态选择指定列?像这样的东西:
var list = new List<Data>(); var result= list.Select("Field1,Field2"); // How ?
这是唯一的解决方案=> 动态LINQ 吗? 所选字段在编译时未知。它们将在运行时指定
您可以通过动态创建传递给的lambda来做到这一点 Select:
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 to Func<Data, Data> return lambda.Compile(); }
然后,您可以像这样使用它:
var result = list.Select( CreateNewStatement( "Field1, Field2" ) );