我使用以下代码成功使用where clause
为equal
创建dynamic linq expression
-
Expression<Func<T, bool>> whereClause = null;
var parameter = Expression.Parameter(typeof(T), "c");
Expression filterExpression = null;
List<Filter> filters = new List<Filter>(){new Filter(){PropertyName= "id" , Value="2" , Operation = "Equal"}}
var DistinctItems = filters.GroupBy(x => x.PropertyName).Select(y => y.First());
foreach (var filterItem in DistinctItems)
{
var member = Expression.Property(parameter, filterItem.PropertyName);
var propertyType = ((PropertyInfo)member.Member).PropertyType;
var converter = TypeDescriptor.GetConverter(propertyType);
if (!converter.CanConvertFrom(typeof(string)))
throw new NotSupportedException();
var propertyValue = converter.ConvertFromInvariantString(filterItem.Value.ToString());
var constant = Expression.Constant(propertyValue);
var valueExpression = Expression.Convert(constant, propertyType);
Expression equality = null;
switch (filterItem.Operation)
{
case "Equal":
equality = Expression.Equal(member, valueExpression);
break;
case "LessThan":
equality = Expression.LessThan(member, valueExpression);
break;
//case "In": how to do for IN forexample where id in
//(1,2)
// equality = Expression.(member, valueExpression);
// break;
}
if (filterExpression == null)
{
filterExpression = equality;
}
else
{
filterExpression = Expression.And(filterExpression, equality);
}
}
if (filterExpression != null)
{
whereClause = Expression.Lambda<Func<T, bool>>(filterExpression, parameter);
}
return whereClause;
如何为IN子句执行此操作,例如 - 其中Id IN(1,2)