Dynamic linq: Dynamic selection of a specific column
When dealing with a class like the
Data
class provided in the problem, it is necessary to choose a specific column during the linq operation. This task can be completed by dynamically created Lambda expressions passed to SELECT method.
For this reason, the
Createnewstatement
Method. It receives a string containing the required field name as input and dynamically constructs Lambda expressions that execute the necessary column. In this method:
Create an expression parameter, indicating the input object passed to Lambda.
Use Expression.new - Method to create a new example of
Data - class.
Use Expression.split Method to divide the input string into a list of single field names.
For each field name, use - Type.getproperty Get the corresponding attributes in the Data
class. -
Use Expression.property The original value of the retrieval attribute.
Use Expression.bind
Create a binding expression to set the attribute value in the new instance. -
Use Expression.memberinit Binded expression into a single initialization expression.
- Finally, use EXPRESSION.LAMBDA Create lambda expression and compile it into appropriate types of commission.
- With the Createnewstatement method, you can call it by using the required field name as a parameter to dynamically select a specific column. For example, select Field1
and - Field2 column: column:
This method provides a common method that dynamically selects columns in the Linq operation. Even if the selected field is not known during compilation.
The above is the detailed content of How Can Dynamic LINQ Select Specific Columns On-Demand?. For more information, please follow other related articles on the PHP Chinese website!
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn