搜索後,我找到了答案,答案是:
public class SearchField
{
public string Name { get; set; }
public string @Value { get; set; }
//public string Operator { get; set; }
public SearchField(string Name, string @Value)
{
this.Name = Name;
[email protected] = @Value;
//Operator = "=";
}
}
public class FilterLinq<T>
{
public static Expression<Func<T, Boolean>> GetWherePredicate(params SearchField[] SearchFieldList)
{
//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 (SearchFieldList != null)
{
foreach (var fieldItem in SearchFieldList)
{
//Expression for accessing Fields name property
Expression columnNameProperty = Expression.Property(pe, fieldItem.Name);
//the name constant to match
Expression columnValue = Expression.Constant(fieldItem.Value);
//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
if (combined != null) return Expression.Lambda<Func<T, Boolean>>(combined, pe);
return null;
}
}
,並使用它像這樣:
var lst = _efmodel.Count(2015).AsQueryable()
.Where(
FilterLinq<PazTedad_Result>.GetWherePredicate(
new SearchField("FieldName", "FieldValue"))).ToList();
這是不平凡的,不維護,一般一個壞主意。考慮重塑你的數據庫或者重構你的代碼,所以你不需要它。如果你能展示_why_你需要這個例子,這將有所幫助。無論如何見[如何在運行時創建表達式](http://stackoverflow.com/questions/19164308/how-to-create-an-expression-at-runtime-for-use-in-groupby-with-entity- framewor),[在LINQ to EF查詢中構建動態where子句](http://stackoverflow.com/questions/14901430/)等等。 – CodeCaster