Linq AND搜索

时间:2015-09-29 07:41:10

标签: c# linq

我有一个名为searchWords的数组,它是一个存储人们搜索词的动态数组。我需要为AND搜索添加一个选项。因此,如果searchWords中的两个变量都包含resultList,则搜索将仅检索项目。现在是searchWords.Any。 searchWords.All会使这个有用吗?

 var resultList = from c in context.Category
     join q in context.Question on c.CategoryId equals q.CategoryId
     join qf in context.QuestionFilter on q.QuestionId equals qf.QuestionId
     join a in context.Answer on q.QuestionId equals a.QuestionId into QuestAnsw
     from a2 in QuestAnsw.DefaultIfEmpty()
     orderby c.SortOrder
     orderby q.SortOrder
     where qf.FilterId == filterKeyAsInt
     && q.Published == true
     && c.Published == true
     && q.CustomerId == customerId
     && (searchWords.Any(w => a2.Text.Contains(w))
     || searchWords.Any(w => c.Text.Contains(w))
     || searchWords.Any(w => q.Text.Contains(w)))
     select new { Category = c, Question = q };

2 个答案:

答案 0 :(得分:0)

如果使用 searchWords.All ,您可以这样做,但我认为 searchWords.Any 更直观。

var resultList = from c in context.Category
     join q in context.Question on c.CategoryId equals q.CategoryId
     join qf in context.QuestionFilter on q.QuestionId equals qf.QuestionId
     join a in context.Answer on q.QuestionId equals a.QuestionId into QuestAnsw
     from a2 in QuestAnsw.DefaultIfEmpty()
     orderby c.SortOrder
     orderby q.SortOrder
     where qf.FilterId == filterKeyAsInt
     && q.Published == true
     && c.Published == true
     && q.CustomerId == customerId
     && !
     (
         searchWords.All(w => !a2.Text.Contains(w))
         && searchWords.All(w => !c.Text.Contains(w))
         && searchWords.All(w => !q.Text.Contains(w))
     )
     select new { Category = c, Question = q };

答案 1 :(得分:0)

您可以在All()中添加多个子句,例如

&& (searchWords.All(w =>
    a2.Text.Contains(w) &&
    c.Text.Contains(w) &&
    q.Text.Contains(w)))
...