6

我有两个大小相同的字符串列表。我想创建一个字典,键是 from listA,值是 from 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方法吗?

4

4 回答 4

14

从 .NET 4.0 开始,您可以使用 LINQ 的Zip方法来完成,如下所示:

var res = ListA.Zip(ListB, (a,b) => new {a, b})
               .ToDictionary(p=>p.a, p=>p.b);

[Zip] 方法将第一个序列的每个元素与第二个序列中具有相同索引的元素合并。

于 2013-01-22T14:00:00.360 回答
4

您可以使用索引创建一个匿名类型,您可以使用该索引来获取B该索引。

Dictionary<string, string> dict = ListA
    .Select((a, i) => new { A = a, Index = i })
    .ToDictionary(x => x.A, x => ListB.ElementAtOrDefault(x.Index));

请注意,如果nullListB小于ListA.

于 2013-01-22T13:59:23.187 回答
2

我不会打扰(如果可能的话),因为您的版本是可读的,易于调试并且比任何其他 LINQ 解决方案都更快(特别是如果您正在使用大列表)。

于 2013-01-22T14:03:57.367 回答
2

我不会改变你的版本。

在您的情况下,以下代码比 LINQ 的内容更具可读性,恕我直言。

var ListA = new List<string>();
var ListB = new List<string>();
var dict = new Dictionary<string, string>();

for (int i = 0; i < ListA.Count; i++)
{
    dict.Add(ListA[i], ListB[i]);
}
于 2013-01-22T14:05:03.677 回答