我有一个搜索表单,允许用户在多种不同的方式几种不同的字段进行搜索。 下面是我的代码的例子。
var claims = from c in db.Claims select c;
switch (ddlSearchField.Text)
{
case "StartsWith":
claims = claims.Where(c => c.companyFileID.StartsWith(txtSearchBox.Text));
break;
case "Equals":
claims = claims.Where(c => c.companyFileID == txtSearchBox.Text);
break;
case "Contains":
claims = claims.Where(c => c.companyFileID.Contains(txtSearchBox.Text));
break;
}
我有十个不同的领域,用户可以搜索,所以我外面的开关语句是相当大的。 必须有做到这一点更优雅的方式。
您可以通过创建一个扩展方法重构代码的某些部分。 类似的东西:
static class QueryableExtensions
{
private static MethodInfo StringContainsMethod;
private static MethodInfo StringStartsWithMethod;
static QueryableExtensions()
{
Type[] singleStringParam = new[] {typeof(string)};
StringContainsMethod = typeof(string).GetMethod("Contains", singleStringParam);
StringStartsWithMethod = typeof(string).GetMethod("StartsWith", singleStringParam);
}
public static IQueryable<T> AppendTextFilter<T>(this IQueryable<T> queryable, Expression<Func<T, string>> memberSelector, string condition, string value)
{
Expression expression = null;
switch (condition)
{
case "StartsWith":
expression = Expression.Call(
memberSelector.Body,
StringStartsWithMethod,
Expression.Constant(value));
break;
case "Equals":
expression = Expression.Equal(
memberSelector.Body,
Expression.Constant(value));
break;
case "Contains":
expression = Expression.Call(
memberSelector.Body,
StringContainsMethod,
Expression.Constant(value));
break;
default:
throw new NotSupportedException(string.Format("'{0}' is not a supported condition", condition));
}
var lambda = Expression.Lambda<Func<T, bool>>(
expression,
memberSelector.Parameters);
return queryable.Where(lambda);
}
}
然后,您可以使用它这样:
var claims = db.Claims
.AppendTextFilter(c => c.companyFileID, ddlSearchField.Text, txtSearchBox.Text)
.AppendTextFilter(c => c.someOtherProperty, ddlOtherSearchField.Text, txtOtherSearchBox.Text)
...;
你有没有试过动态LINQ? 它允许你建立类似于SQL WHERE子句基于字符串的查询语句。
http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx
你可以让你的可能谓词的词典:
Dictionary<string, Func<string, Expression<Func<Claim, bool>>>> map = new Dictionary<string, Func<string, Expression<Func<Claim, bool>>>>() {
{ "StartsWith", t => c => c.companyFileID.StartsWith(t) },
{ "Equals", t => c => c.companyFileID == t },
{ "Contains", t => c => c.companyFileID.Contains(t) }
};
这可能是像这样使用:
var search = ddlSearchField.Text;
var text = txtSearchBox.Text;
var claims = from c in db.Claims select c;
Func<string, Expression<Func<Claim, bool>>> predicate = null;
if(dict.TryGetValue(search, out predicate))
claims = claims.Where(predicate(text));