C#dynamic linq: Realize the dynamic column selection
<code class="language-csharp">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; } }</code>
In order to dynamically implement this, we can dynamically create a lambda expression:
<code class="language-csharp">Func<Data, Data> CreateNewStatement(string fields) { // 输入参数 "o" var xParameter = Expression.Parameter(typeof(Data), "o"); // 新语句 "new Data()" var xNew = Expression.New(typeof(Data)); // 创建初始化器 var bindings = fields.Split(',').Select(o => o.Trim()).Select(o => { // 属性 "Field1" var mi = typeof(Data).GetProperty(o); // 原始值 "o.Field1" var xOriginal = Expression.Property(xParameter, mi); // 设置值 "Field1 = o.Field1" return Expression.Bind(mi, xOriginal); }); // 初始化 "new Data { Field1 = o.Field1, Field2 = o.Field2 }" var xInit = Expression.MemberInit(xNew, bindings); // 表达式 "o => new Data { Field1 = o.Field1, Field2 = o.Field2 }" var lambda = Expression.Lambda<Func<Data, Data>>(xInit, xParameter); // 编译为 Func<Data, Data> return lambda.Compile(); }</code>
Lambda expression. The Lambda expression dynamically creates a new Data object with a specified field value, so as to select these fields. Func<Data, Data>
<code class="language-csharp">var result = list.Select(CreateNewStatement("Field1, Field2"));</code>
The above is the detailed content of How Can Dynamic LINQ Enable Dynamic Column Selection in C#?. For more information, please follow other related articles on the PHP Chinese website!