2017-05-19 5 views
0

これらのコードブロックは同じですか?どちらがいいですか?新しい辞書を(2)で初期化する必要がありますか?Linqと辞書の初期化

XDocument docXml = XDocument.Load(filePath); 

最初のブロック:

var dictionary = new Dictionary<string, string>(); 
var temp = configXml.Root.Element("hs") 
      .Descendants("h") 
      .Select(x => new 
      { 
      a = x.Attribute("a").Value, 
      b = x.Value 
      }); 
      foreach (var c in temp) 
      { 
      dictionary.Add(c.a, c.b); 
      } 

第二のブロック:

ConectionStrings = configXml.Root.Element("hs") 
        .Descendants("h") 
        .ToDictionary(x => x.Attribute("a").Value, 
            x => x.Value); 
+0

'list'とは何ですか?コードブロックはかなり異なるので、どうやって比較すればいいですか? –

+0

申し訳ありませんが、上からの反復です。 2番目のコードブロックで変更値を忘れました。 – dMilan

答えて

1

YESキーによりキーを追加したり、ToDictionaryを使用して両方とも同じです。 .NETソースコードを見ると、次のようになります。

public static Dictionary<TKey, TElement> 
      ToDictionary<TSource, TKey, TElement>(this IEnumerable<TSource> source, 
      Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, 
      IEqualityComparer<TKey> comparer) 
{ 
    if (source == null) throw Error.ArgumentNull("source"); 
    if (keySelector == null) throw Error.ArgumentNull("keySelector"); 
    if (elementSelector == null) throw Error.ArgumentNull("elementSelector"); 
    Dictionary<TKey, TElement> d = new Dictionary<TKey, TElement>(comparer); 
    foreach (TSource element in source) 
    { 
     d.Add(keySelector(element), elementSelector(element)); 
    } 
    return d; 
} 
関連する問題