【问题标题】:How to search through all fields of a table in Lambda如何在 Lambda 中搜索表的所有字段
【发布时间】:2014-03-11 09:33:10
【问题描述】:

这是一个 ASP.NET MVC 项目。 我想从视图中查询具有特定文本框值的数据库表。 这会查询两个字段:

public ActionResult Index(string search)
{
    return View(db.KDtable
                  .Where(x =>
                    x.Name.StartsWith(search)
                    || x.Description.StartsWith(search)
                    || search == null)
                  .ToList()
                );
}

string search 是文本框的值。

问题:

我怎样才能,而不是手动将所有字段添加到 lambda 表达式,例如x.City.StartsWith(search),使用文本框的输入简单查询所有表字段。

谢谢

【问题讨论】:

标签: c# asp.net-mvc lambda


【解决方案1】:

试试这个:

public static Expression<Func<T,bool>> CreateTextSearch<T>(string searchText)
{
    Type t = typeof(T);
    var props = t.GetProperties().Cast<PropertyInfo>().Where(p => p.PropertyType == typeof(string));

    var searchTextExpr = Expression.Constant(searchText);
    var tParameterExpr = Expression.Parameter(typeof(T));

    Expression expr = null;
    foreach(var prop in props)
    {
        var criteria = Expression.Call(
            Expression.Property(tParameterExpr, prop),
            typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) }),
            searchTextExpr);
        if(expr == null)
            expr = criteria;
        else
            expr = Expression.Or(expr, criteria);
    }
    return Expression.Lambda<Func<T,bool>>(expr, tParameterExpr);
}

这样称呼它:MySet.Where(CreateTextSearch&lt;MyType&gt;("DDD")); 用于 IQueryables,MySet.Where(CreateTextSearch&lt;MyType&gt;("DDD").Compile()); 用于常规 IEnumerables。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-31
    • 1970-01-01
    • 1970-01-01
    • 2021-07-23
    • 1970-01-01
    相关资源
    最近更新 更多