Dynamic query in LINQ

后端 未结 5 1315
不思量自难忘°
不思量自难忘° 2021-02-11 06:56

How do I write a dynamic query for Linq, if I have say Customer class which holds the fields:

string name
string address
int phoneno

I have to

5条回答
  •  北恋
    北恋 (楼主)
    2021-02-11 07:34

    It sounds like you need to dynamically compose queries.

    See my answer to this question.

    It explains how queries against an IQueryable are composed by the compiler, and what you can do to add dynamic elements.

    Edit

    Here is an example of how you would dynamically build a set of Where conditions on top of an IQueryable:

    // This method ANDs equality expressions for each property, like so:
    //
    // customers.Where(c => c.Property1 == value1 && c.Property2 == value2 && ...);
    
    private IQueryable FilterQuery(IQueryable customers, IDictionary filter)
    {
        var parameter = Expression.Parameter(typeof(Customer), "c");
        Expression filterExpression = null;
    
        foreach(var filterItem in filter)
        {
            var property = typeof(Customer).GetProperty(filterItem.Key);
            var propertyAccess = Expression.MakeMemberAccess(parameter, property);
            var equality = Expression.Equal(propertyAccess, Expression.Constant(filterItem.Value));
    
            if(filterExpression == null)
            {
                filterExpression = equality;
            }
            else
            {
                filterExpression = Expression.And(filterExpression, equality);
            }
        }
    
        if(filterExpression != null)
        {
            var whereBody = Expression.Lambda>(filterExpression, parameter);
    
            customers = customers.Where(whereBody);
        }
    
        return customers;
    }
    

提交回复
热议问题