Home >Backend Development >C++ >How Can I Dynamically Select Specific Columns in LINQ?
Assuming the following scene: You have a Data class containing multiple fields, and you want to select a specific column based on the input dynamic provided by the user. This brings a challenge because the selected field is unknown when compiling.
Dynamic Lambda expression creation
In order to overcome this obstacle, we can dynamically create a Lambda expression that executes the selected. The method is as follows:
How to use
<code class="language-csharp">public Func<Data, Data> CreateNewStatement(string fields) { // 参数 var xParameter = Expression.Parameter(typeof(Data), "o"); // 新实例 var xNew = Expression.New(typeof(Data)); // 初始化器 var bindings = fields.Split(',') .Select(o => o.Trim()) .Select(o => { var mi = typeof(Data).GetProperty(o); var xOriginal = Expression.Property(xParameter, mi); return Expression.Bind(mi, xOriginal); }); // 初始化 var xInit = Expression.MemberInit(xNew, bindings); // Lambda表达式 var lambda = Expression.Lambda<Func<Data, Data>>(xInit, xParameter); // 编译 return lambda.Compile(); }</code>With Lambda creation functions, you can now execute dynamic choices:
This will create a Lambda expression that dynamically selects "Field1" and "Field2" properties to effectively perform custom projection of data.
Conclusion
<code class="language-csharp">var result = list.Select(CreateNewStatement("Field1, Field2"));</code>
Using this technology, you can overcome the restrictions of the static definition of Linq projection, and enable the dynamic selection according to the input. This allows greater flexibility and adaptability to achieve greater flexibility and adaptability in the data processing scenario that is not known in advance.
The above is the detailed content of How Can I Dynamically Select Specific Columns in LINQ?. For more information, please follow other related articles on the PHP Chinese website!