2011-03-19 6 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呼び出しを移動します。これは、変換からXAttributestring戻りをnullという事実を使用しています

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); 

:あなたは少し単純すぎるけれども、あなたのクエリを作ることができます

...自分で実装する問題を抱えた場所それは私にははっきりしていません属性参照自体がnullの場合私は自分自身のための言い訳をしないようにしてくださいよ

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

あなたも、クエリ式を使用する必要はありません。私は木の木が見えないと思う。私は問題を再訪したときに自分の処方薬を飲んでいただろう。パフォーマンスの向上だけでなく、おそらく私が気付いていなかった簡素化のために掲示する価値がありました - ありがとうジョン – CarneyCode

関連する問題