2012-06-07 31 views
1

我試圖在xml文件中查詢搜索項的兩個屬性。Linq-to-xml其中或子句

我有這樣的:

<?xml version="1.0" encoding="utf-8" ?> 
<Products> 
    <item ProductName="Golf Shirt" Content="This is a nice breathable shirt for golf." /> 
    <item ProductName="Bowling Ball" Content="This is a colorful 8-lbs ball." /> 
    <item ProdcutName="Tee Shirt" Content="100% cotton tee-shirt." /> 
</Products> 

我要查詢這兩個產品名稱和內容屬性值的搜索詞。

這裏是我的查詢表達式:

var results = from node in _xDoc.Descendants("Item") 
    where node.Attribute("Content").Value.Contains(searchTerm) 
    where node.Attribute("ProductName").Value.Contains(searchTerm) 
    select new SearchModel() 
    { 
    Name = node.Attribute("ProductName").Value, 
    Url = "the url", 
    Group = "Products" 
    }; 

如果我的搜索詞是「襯衫」,我應該回到「高爾夫襯衫」和「T恤」,但我什麼也沒得到。我認爲這是因爲雙「where」子句創造和「和」表達,我需要一個「或」表達式。如果我刪除其中一個「where」子句,它就可以工作。

我試着把一個「||」在第一個「where」子句之後,但是會產生一個錯誤。

如何爲Linq-to-Xml實現「或where」子句?

謝謝。

回答

0

你有沒有嘗試過這樣的事情:

where ((string)node.Attribute("Content")).Contains(searchTerm) || ((string)node.Attribute("ProductName")).Contains(searchTerm) 

+0

是的,我剛剛發現它和你的答案非常相似。 – Kahanu

0

我想通了。這是我的修復。

var results = _xDoc.Descendants("Item") 
    .Where(c => 
     (
      c.Attribute("ProductName").Value.ToLower().Contains(searchTerm.ToLower()) || 
      c.Attribute("Content").Value.ToLower().Contains(searchTerm.ToLower()) 
     ) 
    ) 
    .Select(c => new SearchModel() 
     { 
      Name = c.Attribute("ProductName").Value, 
      Url = "the url", 
      Group = "Products" 
     });