Match two lists in a dictionary in C #

Given two IEnumerable 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 result:

 A: Val A B: Val B C: Val C 

I wonder if there is any simple way to achieve it.

And do you have to worry about performance? What if I have large collections?




I don’t have, if there is an easier way to do this, currently I am doing this:

I have an extension method that will quote IEnumerable , giving me the element and 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 Enumerables and with an index get the equivalent element on another 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 
+47
dictionary c # linq ienumerable
Oct 28 '10 at 1:14
source share
3 answers

With .NET 4.0 (or version 3.5 of System.Interactive from Rx) you can use Zip() :

 var dic = keys.Zip(values, (k, v) => new { k, v }) .ToDictionary(x => xk, x => xv); 
+98
Oct 28 '10 at 1:16
source share

Or based on your idea, LINQ includes Select() overloading, which provides an index. Combined with the fact that values supports index access, you can do the following:

 var dic = keys.Select((k, i) => new { k, v = values[i] }) .ToDictionary(x => xk, x => xv); 

(If values is stored as List<string> , that is ...)

+20
Oct 28 '10 at 1:21
source share

I like this approach:

 var dict = Enumerable.Range(0, keys.Length).ToDictionary(i => keys[i], i => values[i]); 
+7
Jun 12 '14 at 17:44
source share



All Articles