Dynamic query in LINQ

后端 未结 5 706
甜味超标
甜味超标 2021-02-11 06:47

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:33

    I've had good experience with Dynamic LINQ.

    I used it for a rich HTML table that could be filtered and sorted server side. The server receives a request containing a request parameter where the key is the name of the property (for example 'Lastname') and the value is the value that the property needs to be sorted on (for example 'Smith'). Using that information I built a query string that I passed to the Dynamic LINQ's Where method.

    Roughly, you could think of something like the following:

    public static IQueryable Filter(this IQueryable query, Dictionary dictionary)
    {
        Type t = typeof(T);
        StringBuilder sb = new StringBuilder();
            PropertyInfo[] properties = t.GetProperties();
            foreach(string key in dictionary.Keys)
            {
                PropertyInfo property = properties.Where(p => p.Name == key).SingleOrDefault();
                if(property != null)
                {
                    if (sb.Length > 0) sb.Append(" && ");
    
                    string value = dictionary[key];
    
                    sb.Append(string.Format(@"{0}.ToString().Contains(""{1}"")", key, value));
                }
            }
    
            if (sb.Length > 0)
            return query.Where(sb.ToString());
        else
                return query;
    }
    

    The code is out of the top of my head and thus untested.

    Of course, this is the most basic version: it does a simple string comparison. If you want to have numerical comparison (meaning you want for example the User where UserID is exactly 100, not where the UserID.ToString().Contains("100")), or query nested Properties (Customer.Company.CompanyAddress for example), or query Collections this gets more complicated. You should also think about security: while Dynamic LINQ is not vulnerable to SQL injection, you shouldn't let it blindly parse all user input.

提交回复
热议问题