C# dynamic linq: Selective projection data attributes
In C#, Linq (Language Integration) can achieve efficient data operation by providing simple statement grammar. However, when processing dynamic data or unknown field names, selective projection may be difficult.
Considering the following scenarios: We have a class that indicates multiple fields, and we want to dynamically choose only specific columns. For example, the Data class that gives us, its fields are Field1, Field2, Field3, Field4, and Field5. We may want to projected a new list, including only Field1 and Field2.
Dynamic Lambda expression creation
In order to achieve this dynamic choice, we can use the powerful features created by dynamic Lambda expressions. We don't have to choose a new Lambda expression dynamically in the Linq statement.
The following is the method we can perform this operation:
This function uses the required field name as a string and returns a
commission to perform selective projection.<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>
Usage Func<Data, Data>
Now, we can use the dynamic lambda expression in the Linq statement:
Function generates a lambda expression, which projected a new Data object, which only contains the specified field, enabling us to dynamically select columns during runtime.This Revised Response Maintains The Improves The Code Formatting for Better Readability. nd Flow.
The above is the detailed content of How Can Dynamic Lambda Expressions Enable Selective Data Projection in C# LINQ at Runtime?. For more information, please follow other related articles on the PHP Chinese website!