我有一個使用linq的請求查詢。該查詢有多個where子句,表示與名稱和城市匹配的項目的返回列表。下面是我用於多個where子句的代碼段,但它返回空的項集。 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 });
}
}
你的例子有效。當然它只適用於字符串屬性,但我認為,這是你的用例。也許它沒有做你想要實現的目標,因為你將你的子句與和結合起來,但實際上你確實想用Or做,jus改變這個代碼行:
combined = Expression.And(combined, e1);
至
combined = Expression.Or(combined, e1);