简体   繁体   English

linq中的动态多个where子句c#

[英]Dynamic multiple where clause in linq c#

I have a request query using linq. 我有一个使用linq的请求查询。 The query has multiple where clause say return list of items matching name and city. 该查询有多个where子句,表示与名称和城市匹配的项目的返回列表。 Below is the piece of code I used for multiple where clause, but it returns empty set of items. 下面是我用于多个where子句的代码段,但它返回空的项集。 wherefield contains list of field names like name;city wherefieldValue contains list of field values like james;delhi wherefield包含字段名称列表,如name; city wherefieldValue包含字段值列表,如james; delhi

 var where = FilterLinq<T>.GetWherePredicate(wherefield, wherefieldvalue).Compile();
 items = items.Where(where).OrderByDescending(a => a.GetType().GetProperty(field).GetValue(a, null)).Skip

 public class FilterLinq<T>
 {
    public static Expression<Func<T, Boolean>> GetWherePredicate(string whereFieldList, string whereFieldValues)
    {
        //the 'IN' parameter for expression ie T=> condition
        ParameterExpression pe = Expression.Parameter(typeof(T), typeof(T).Name);

        //combine them with and 1=1 Like no expression
        Expression combined = null;
        if (whereFieldList != null)
        {
            string[] field = whereFieldList.Split(';');
            string[] fieldValue = whereFieldValues.Split(';');
            for (int i = 0; i < field.Count(); i++)
            {
                //Expression for accessing Fields name property
                Expression columnNameProperty = Expression.Property(pe, field[i]);

                //the name constant to match 
                Expression columnValue = Expression.Constant(fieldValue[i]);

                //the first expression: PatientantLastName = ?
                Expression e1 = Expression.Equal(columnNameProperty, columnValue);

                if (combined == null)
                {
                    combined = e1;
                }
                else
                {
                    combined = Expression.And(combined, e1);
                }
            }
        }

        //create and return the predicate
        return Expression.Lambda<Func<T, Boolean>>(combined, new ParameterExpression[] { pe });
    }
}

Your example works. 你的例子有效。 Sure it works only for string properties, but i assume, that is your use case. 当然它只适用于字符串属性,但我认为,这是你的用例。 Perhaps it doesn't do what you want to achieve, becasue you combine your clause with and, but actually you do want to do it with Or, jus change this code line : 也许它没有做你想要实现的目标,因为你将你的子句与和结合起来,但实际上你确实想用Or做,jus改变这个代码行:

combined = Expression.And(combined, e1);

To

combined = Expression.Or(combined, e1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM