LINQ中是否有OR子句?

时间:2012-03-01 03:00:18

标签: linq

我正在尝试查询XML文档以获取我需要的特定记录。我知道下面包含“或者where”案例的行是不正确的,但我希望它能说明我想要完成的任务。你能在两个单独的属性上做一个条件的where子句吗?

XDocument xd = XDocument.Load("CardData.xml");
SearchList.ItemsSource = from x in xd.Descendants("card")
                         where x.Element("title").Value.ToUpper().Contains(searchterm.ToUpper())
                         or where x.Element("id").Value.Contains(searchterm)
                         select new Card
                         {
                             Title = x.Element("title").Value
                         };

1 个答案:

答案 0 :(得分:2)

是 - 只需使用布尔值或||并将您的条件合并为一个Where子句:

where x.Element("title").Value.ToUpper().Contains(searchterm.ToUpper()) || 
      x.Element("id").Value.Contains(searchterm)

另外请注意,作为一个小优化,我会预先计算你在Where子句中当前拥有的一些操作,这样它们就不会对列表中的每个项目执行 - 可能无关紧要,但是当你有很多元素(在我看来,这只是一个很好的习惯):

string searchTermUpperCase = searchterm.ToUpper();
SearchList.ItemsSource = from x in xd.Descendants("card")
                         where x.Element("title").Value.ToUpper().Contains(searchTermUpperCase)
                         or where x.Element("id").Value.Contains(searchterm)
                         ..