2013-02-05 104 views
1

如何優化此查詢&轉換爲lambda?Linq查詢優化

XElement xde = new XElement("Elements", (from a in rootElement.Elements("Class") 
        where a.Attribute("Location").Value.Equals("FirstFloor") 
        select (from b in a.Elements("Subject") 
          where b.Attribute("Notify").Value.Equals("001") 
          select b.Elements()))); 
+1

Dude認真http://stackoverflow.com/faq#howtoask –

+1

什麼要優化?可讀性?性能?防禦性?另外,請務必解釋您目前遇到的問題。 –

回答

3

就性能而言,我認爲你的查詢不能被優化。

Hoewever可以使其更具可讀性repacing Equals通過==和取出不必要select

XElement xde = 
     new XElement("Elements", (from a in rootElement.Elements("Class") 
            where a.Attribute("Location").Value == "FirstFloor" 
            from b in a.Elements("Subject") 
            where b.Attribute("Notify").Value == "001" 
            select b.Elements())); 
2

你可以簡單的情況下,節點string而不是讀取節點的值。因此,如果xml中缺少屬性,您將避免異常。此外,我建議你使用範圍變量名,其對應的元素名稱(更好的可讀性):

XElement xde = 
    new XElement("Elements", 
     from c in rootElement.Elements("Class") 
     where (string)c.Attribute("Location") == "FirstFloor" 
     from s in c.Elements("Subject") 
     where (string)s.Attribute("Notify") == "001" 
     select s.Elements()); 

還可以考慮使用的XPath(所有查詢將適合一行):

new XElement("Elements", rootElement 
.XPathSelectElements("Class[@Location='FirstFloor']/Subject[@Notify='001']/*")); 

Lambda(你想要的方法語法也是):

new XElement("Elements", 
    rootElement.Elements("Class") 
       .Where(c => (string)c.Attribute("Location") == "FirstFloor") 
       .Elements("Subject") 
       .Where(s => (string)s.Attribute("Notify") == "001") 
       .Elements());