C# Linq和字典初始化
这些代码块是相同的吗?哪一个更好?我应该在(2)处初始化新词典吗 第一个街区:C# Linq和字典初始化,c#,linq,dictionary,C#,Linq,Dictionary,这些代码块是相同的吗?哪一个更好?我应该在(2)处初始化新词典吗 第一个街区: var dictionary = new Dictionary<string, string>(); var temp = configXml.Root.Element("hs") .Descendants("h") .Select(x => new { a = x.Attribute("a").Value,
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);
}
是,按键添加或使用
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;
}
公共静态字典
ToDictionary(此IEnumerable来源,
Func键选择器、Func元素选择器、,
IEqualityComparer(比较器)
{
if(source==null)抛出错误.ArgumentNull(“source”);
if(keySelector==null)抛出错误.ArgumentNull(“keySelector”);
if(elementSelector==null)抛出Error.ArgumentNull(“elementSelector”);
字典d=新字典(比较器);
foreach(源中的TSource元素)
{
d、 添加(键选择器(元素)、元素选择器(元素));
}
返回d;
}
什么是列表
?代码块是完全不同的,那么我们应该如何比较它们呢?对不起,这只是上层的错误安排。我忘记了在第二个代码块更改值。
ConectionStrings = configXml.Root.Element("hs")
.Descendants("h")
.ToDictionary(x => x.Attribute("a").Value,
x => x.Value);
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;
}