如何在LINQ Where语句中使用OR语句

时间:2014-02-21 07:45:36

标签: c# linq

基本上,我想查看给定字符串是否包含在四个数据库条目之一中。 我想要做的例子:

if (!String.IsNullOrEmpty(searchTagName))
{

   Articles = Articles.Where(b => b.Tag1.Contains(searchTagName));
   OR
   Articles = Articles.Where(b => b.Tag2.Contains(searchTagName));
   OR
   Articles = Articles.Where(b => b.Tag3.Contains(searchTagName));
   OR
   Articles = Articles.Where(b => b.Tag4.Contains(searchTagName));
}

我怎样才能写出正确的

语句?

2 个答案:

答案 0 :(得分:6)

你应该从中创建一个lambda表达式:

    if (!String.IsNullOrEmpty(searchTagName))
    {
       Articles = Articles.Where(b => 
                b.Tag1.Contains(searchTagName) ||
                b.Tag2.Contains(searchTagName) || 
                b.Tag3.Contains(searchTagName) ||
                b.Tag4.Contains(searchTagName));
    }

答案 1 :(得分:2)

像这样:

if (!String.IsNullOrEmpty(searchTagName))
{
   Articles = Articles.Where(b => 
                    b.Tag1.Contains(searchTagName) 
                 || b.Tag2.Contains(searchTagName) 
                 || b.Tag3.Contains(searchTagName) 
                 || b.Tag4.Contains(searchTagName));
}