2012-11-15 69 views
0

我想從XDocument中選擇元素,並在單個lambda表達式中爲每個元素添加一個屬性。這是我想要的:C#Linq To Xml - 如何選擇元素集合並使用lambda修改每個元素?

xhtml.Root.Descendants() 
      .Where(e => e.Attribute("documentref") != null) 
      .Select(e => e.Add(new XAttribute("documenttype", e.Attribute("documentref").Value))); 

什麼是正確的方法來做到這一點?

謝謝!

回答

0
xhtml.Root.Descendants() 
      .Where(e => e.Attribute("documentref") != null) 
      .ToList() 
      .ForEach(e => e.Add(new....)); 
1

由於延遲執行LINQ,如果語句的結果從未迭代過,則屬性將不會被添加到XML中。

var elementsWithAttribute = from e in xhtml.Root.Descendants() 
          let attribute = e.Attribute("documentref") 
          where attribute != null 
          select e; 

foreach (var element in elementsWithAttribute) 
    element.Add(...);