使用LINQ使用2个列表创建字典

VNa*_*haM 16 c# linq

我试图从2个列表创建一个字典,其中一个列表包含键,一个列表包含值.我可以使用for循环,但我试图找到是否有办法使用LINQ.示例代码将非常有用.谢谢!!!!

Luk*_*keH 44

在.NET4中,您可以使用内置Zip方法合并两个序列,然后ToDictionary调用:

var keys = new List<int> { 1, 2, 3 };
var values = new List<string> { "one", "two", "three" };

var dictionary = keys.Zip(values, (k, v) => new { Key = k, Value = v })
                     .ToDictionary(x => x.Key, x => x.Value);
Run Code Online (Sandbox Code Playgroud)


Jak*_*ake 20

        List<string> keys = new List<string>();
        List<string> values = new List<string>();
        Dictionary<string, string> dict = keys.ToDictionary(x => x, x => values[keys.IndexOf(x)]);
Run Code Online (Sandbox Code Playgroud)

这当然假设每个列表的长度相同并且键是唯一的.

更新: 这个答案效率更高,应该用于非平凡大小的列表.

  • 因为使用上面的代码,它必须对每个键的键的List <strign>中的元素x进行线性搜索(在O(n)时间内).在循环中,索引在每次迭代时都是已知的,因此不需要搜索. (12认同)