加入LINQ中的列并运行包含运算符

时间:2012-07-30 13:28:37

标签: c# asp.net linq webforms

我正在尝试创建一个搜索方法,我想检查关键字是否包含在给定记录的任意数量的不同列中。

我的Linq声明如下:

string[] searchFilter = {"john", "iceberg"};


var q = from qua in qual
                    join del in deliverables on qua.ID equals del.Q_ID
                    where searchFilter.All(s => (qua.Name + " " + qua.Project + " " + qua.Summary + " " + del.Name + " " + del.Summary).ToLower().Contains(s))
                    select qua;

但是我收到一条错误消息,指出:“除了Contains()运算符之外,本地序列不能用于查询运算符的LINQ to SQL实现。”

3 个答案:

答案 0 :(得分:1)

确实你不能使用All方法,只能使用Contains方法:

var q = from qua in qual
        join del in deliverables on qua.ID equals del.Q_ID
        where searchFilter.Contains(qua.Name) ||  searchFilter.Contains(qua.Project)...
        select qua;

当然,你可以动态地将linq查询与表达式结合起来(但可能会有更多工作),或者使用动态linq。

答案 1 :(得分:1)

不要以为你有选择:

但是当你留在“可查询”世界时,这将只生成一个sql请求(丑陋,但是......)

var q = from qua in qual
        join del in deliverables on qua.ID equals del.Q_ID
        select new{ qua, del};

foreach (var filter in searchFilter)
     q = q.Where(v => (v.qua.Name + " " + v.qua.Project + " " + v.qua.Summary + " " + v.del.Name + " " + v.del.Summary).ToLower().Contains(filter));

var result = q.Select(p => p.qua);

答案 2 :(得分:0)

无论出于何种原因,contains方法在第二次循环时都没有使用过滤结果。最终起作用的方法是:

var SearchColumn = from qua in Qual
               join del in deliverables on qua.Q_ID equals del.Q_ID into left_j
                            from del in left_j.DefaultIfEmpty()
                            select new { qua.Name + " " + qua.Project + " " + qua.Summary + " " + del.Name + " " + del.Summary).ToLower() };

foreach (var f in searchFilter)
{
   var likestr = string.Format("%{0}%", f);
   SearchColumn = SearchColumn.Where(x => SqlMethods.Like(x.Search_Col, likestr));
}