我有一个使用linq的请求查询。该查询有多个where子句,表示与名称和城市匹配的项目的返回列表。 下面是我用于多个where子句的代码段,但它返回空的项集。 wherefield包含名称,城市等字段名称列表 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 });
}
}
答案 0 :(得分:0)
你的例子有效。当然它只适用于字符串属性,但我认为,这是你的用例。 也许它没有做你想要实现的目标,因为你将你的子句与和结合起来,但实际上你确实希望用Or来做,jus改变这个代码行:
combined = Expression.And(combined, e1);
要
combined = Expression.Or(combined, e1);