Home >Backend Development >C++ >How Can Dynamic LINQ Enable Dynamic Column Selection in C#?
<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>Suppose you want to dynamically select a specific column from the list of Data objects, for example, only Field1 and Field2. During the scene of the selected field and you must specify these fields at runtime, using dynamic linq is an effective method.
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>This method accepts the string of the required field name as the input, and returns a
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>Even if you do n’t know the selected field during compilation, this can also provide dynamic and flexible solutions for selecting columns in the Linq query.
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!