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!!!!
+3
A:
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)]);
This of course assumes that the length of each list is the same and that the keys are unique.
Jake
2010-03-12 17:35:51
I'd rather use a loop, instead of using this. Still +1 for the answer.
Steven
2010-03-12 17:41:07
That was it. Thanks!!!
VNarasimhaM
2010-03-12 17:41:14
why would you use loops instead of LINQ? I thought this code is lot more succint and readable than the for loop.
VNarasimhaM
2010-03-12 17:46:30
Because with the code above it has to do a linear search for the element x in the List<strign> of keys for every key (In O(n) time). In a loop the index is known at each iteration so no search is necessary.
Paul Ruane
2010-03-12 18:49:46
A:
var a = new List<string>() { "A", "B", "C" };
var b = new List<string>() { "1", "2", "3" };
var c = a.Select((x, i) => new {key = x, value = b[i]}).ToDictionary(e => e.key, e => e.value );
foreach (var d in c)
Console.WriteLine(d.Key + " = " + d.Value);
Console.ReadKey();
Hightechrider
2010-03-12 17:40:21
+2
A:
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);
LukeH
2010-03-12 17:40:56