地图两个列表成为在C#中词典 [英] Map two lists into a dictionary in C#
问题描述
给定两个 的IEnumerable
取值,我怎么能转换为 词典
使用LINQ?
的IEnumerable<字符串>键=新的名单,其中,串>(){A,B,C};
IEnumerable的<字符串>值=新的名单,其中,串>(){瓦尔A,瓦尔B,瓦尔C};
VAR词典= / * LINQ的? * /;
和预期的输出结果是:
A:瓦尔一
B:瓦尔乙
C:瓦尔Ç
我不知道是否有一些简单的方法去实现它。
和我应该担心的表现?如果我有大集合?
我不知道,如果有一个更简单的方法来做到这一点,目前我在做这样的:
我有一个扩展方法,将循环中的的IEnumerable
我提供的元素和索引号。
公共静态类内线
{
公共静态无效每个< T>(这IEnumerable的ELS,动作< T,INT>将)
{
INT I = 0;
的foreach(在ELS率T e)
{
一(E,I ++);
}
}
}
和我有一个将循环可枚举的索引和一个检索其他可枚举等效元法。
公共静态字典< TKEY的,TValue>合并< TKEY的,TValue>(IEnumerable的< TKEY的>键,IEnumerable的< TValue>数值)
{
VAR DIC =新字典< TKEY的,TValue>();
keys.Each< TKEY的>((X,I)=>
{
dic.Add(X,values.ElementAt(ⅰ));
});
返回DIC;
}
然后,我用它喜欢的:
的IEnumerable<字符串>键=新的名单,其中,串>(){A,B,C};
IEnumerable的<字符串>值=新的名单,其中,串>(){瓦尔A,瓦尔B,瓦尔C};
VAR DIC = Util.Merge(键,值);
和输出是正确的:
A:瓦尔一
B:瓦尔乙
C:瓦尔Ç
使用.NET 4.0(或接收的3.5版本System.Interactive的),你可以使用邮编()
:
VAR DIC = keys.Zip(值,(K,V)=>新建{K,V})
.ToDictionary(X => x.k中,x => x.v);
Given two IEnumerable
s of the same size, how can I convert it to a Dictionary
using Linq?
IEnumerable<string> keys = new List<string>() { "A", "B", "C" };
IEnumerable<string> values = new List<string>() { "Val A", "Val B", "Val C" };
var dictionary = /* Linq ? */;
And the expected output is:
A: Val A
B: Val B
C: Val C
I wonder if there is some simple way to achieve it.
And should I be worried about performance? What if I have large collections?
I don't if there is an easier way to do it, currently I'm doing like this:
I have an Extension method that will loop the IEnumerable
providing me the element and the index number.
public static class Ext
{
public static void Each<T>(this IEnumerable els, Action<T, int> a)
{
int i = 0;
foreach (T e in els)
{
a(e, i++);
}
}
}
And I have a method that will loop one of the Enumerables and with the index retrieve the equivalent element on the other Enumerable.
public static Dictionary<TKey, TValue> Merge<TKey, TValue>(IEnumerable<TKey> keys, IEnumerable<TValue> values)
{
var dic = new Dictionary<TKey, TValue>();
keys.Each<TKey>((x, i) =>
{
dic.Add(x, values.ElementAt(i));
});
return dic;
}
Then I use it like:
IEnumerable<string> keys = new List<string>() { "A", "B", "C" };
IEnumerable<string> values = new List<string>() { "Val A", "Val B", "Val C" };
var dic = Util.Merge(keys, values);
And the output is correct:
A: Val A
B: Val B
C: Val C
With .NET 4.0 (or the 3.5 version of System.Interactive from Rx), you can use Zip()
:
var dic = keys.Zip(values, (k, v) => new { k, v })
.ToDictionary(x => x.k, x => x.v);
这篇关于地图两个列表成为在C#中词典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!