我有两个大小相同的字符串列表。我想创建一个字典,键来自listA,值来自listB。
最快的方法是什么?
我使用了以下代码:
List<string> ListA;
List<string> ListB;
Dictionary<string,string> dict = new Dictionary<string,string>();
for(int i=0;i<ListA.Count;i++)
{
dict[key] = listA[i];
dict[value]= listB[i];
}我不喜欢这种方式,我可以使用ToDictionary方法吗?
发布于 2013-01-22 22:00:00
从Linq4.0开始,您可以使用.NET的Zip方法完成此操作,如下所示:
var res = ListA.Zip(ListB, (a,b) => new {a, b})
.ToDictionary(p=>p.a, p=>p.b);Zip方法将第一个序列中的每个元素与第二个序列中具有相同索引的元素合并。
发布于 2013-01-22 21:59:23
您可以创建一个带有索引的匿名类型,您可以使用它来获取此索引处的B。
Dictionary<string, string> dict = ListA
.Select((a, i) => new { A = a, Index = i })
.ToDictionary(x => x.A, x => ListB.ElementAtOrDefault(x.Index));请注意,如果ListB小于ListA,则该值将为null。
发布于 2013-01-22 22:03:57
我不会麻烦(如果它是可能的),因为你的版本是可读性的,易于调试,比任何其他LINQ解决方案更快(特别是如果你正在处理大列表)。
https://stackoverflow.com/questions/14460239
复制相似问题