通过创建使用LINQ 2列出了一本字典 [英] create a dictionary using 2 lists using LINQ

查看:85
本文介绍了通过创建使用LINQ 2列出了一本字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建2列出了一本字典,其中一个列表中包含键和一个列表包含的值。我可以使用循环,但我想找到是否有使用LINQ做它的方式做。
示例代码将是有益的。谢谢!!!!

I am trying to create a dictionary from 2 lists where one list contains keys and one list contains values. I can do it using for loop but I am trying to find if there is a way of doing it using LINQ. Sample code will be helpfull. Thanks!!!!

推荐答案

在.NET4你可以使用内置的 邮编 法合并两个序列,随后 ToDictionary 拨打:

In .NET4 you could use the built-in Zip method to merge the two sequences, followed by a ToDictionary call:

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

这篇关于通过创建使用LINQ 2列出了一本字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆