2011-03-19 42 views
2

今天早上我真的需要去別的地方。所以,我決定在這裏發佈一個性能問題。你能改善這個linq-to-xml方法的性能嗎?

下面的代碼工作,但它多次調用Load和Save方法。這似乎遠沒有效率。請有人提供代碼到目前爲止加載和保存線出現在循環之外。我想調用加載並保存一次。

感謝傢伙:)

public void RemoveNodes(IList<String> removeItems) 

    { 

     foreach (String removeItem in removeItems) 

     { 

      XDocument document = XDocument.Load(fullFilePath); 

      var results = from item in document.Descendants(elementName) 

          let attr = item.Attribute(attributeName) 

          where attr != null && attr.Value == removeItem.ToString() 

          select item; 

      results.ToList().ForEach(item => item.Remove()); 

      document.Save(fullFilePath); 

     } 

    } 

回答

2

你已經給自己的答案 - 只要將外循環LoadSave電話。

XDocument document = XDocument.Load(fullFilePath); 
foreach (String removeItem in removeItems) 
{ 
    var results = from item in document.Descendants(elementName) 
        where (string) item.Attribute(attributeName) == removeItem 
        select item; 
    results.ToList().ForEach(item => item.Remove()); 
} 
document.Save(fullFilePath); 

它使用的事實,轉化率從XAttributestring返回null:你在哪裏有實現一個自己...

你可以讓你查詢稍微簡單過問題,但目前尚不清楚對我如果該屬性引用本身爲空。

你甚至都不需要使用查詢表達式:

var results = document.Descendants(elementName) 
      .Where(item => (string) item.Attribute(attributeName) == removeItem); 
+0

我會盡量找藉口爲自己。我想我看不到樹木。當我重新審視這個問題時,我會喝我自己的處方藥。值得注意的不僅僅是因爲性能的提升,而是我可能不會注意到的一種簡化 - 感謝Jon – CarneyCode 2011-03-19 09:51:08