【问题标题】:Linq and dictionary initialization [closed]Linq 和字典初始化
【发布时间】:2017-05-19 09:12:37
【问题描述】:

这些代码块是否相同?哪一个更好?我应该在 (2) 处初始化新字典吗?

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

【问题讨论】:

  • 什么是list?代码块差别很大,应该如何比较呢?
  • 对不起,它只是从上层迭代。我忘记了第二个代码块的更改值。

标签: c# linq dictionary


【解决方案1】:

是的,一键添加或使用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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-30
    • 2012-04-27
    • 2017-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-17
    • 2018-07-14
    相关资源
    最近更新 更多