Home >Backend Development >C++ >How Can I Dynamically Select Columns in LINQ Queries?

How Can I Dynamically Select Columns in LINQ Queries?

Susan Sarandon
Susan SarandonOriginal
2025-01-28 19:56:10986browse

How Can I Dynamically Select Columns in LINQ Queries?

Dynamic columns in linq selection

When the list is unknown, the specific column in the LINQ query may be challenging. However, there is a solution involving the Lambda expression passed to Select.

Consider the following data class:

In order to dynamically select a specific column, you can use the Createnewstatement method to dynamically create lambda expressions:
<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>

This method uses the list of the comma to separate the list as a string, and dynamically generates a lambda expression. This expression initializes a new data object using a specified field.
<code class="language-csharp">private 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);
    var lambda = Expression.Lambda<Func<Data, Data>>(xInit, xParameter);
    return lambda.Compile();
}</code>

Then you can use the Createnewstatement method to create lambda expressions and pass it to select:

This will return a sequence with a Data object filled in a specified field. Please note that this technology is suitable for the unknown field when compiling. If the selected field is static, the conventional LAMBDA expression or reflex -based method is more efficient.
<code class="language-csharp">var result = list.Select(CreateNewStatement("Field1, Field2"));</code>

The above is the detailed content of How Can I Dynamically Select Columns in LINQ Queries?. 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