Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create a dictionary using 2 lists using LINQ

Tags:

c#

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!!!!

like image 344
VNarasimhaM Avatar asked Mar 12 '10 17:03

VNarasimhaM


2 Answers

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);
like image 86
LukeH Avatar answered Sep 19 '22 05:09

LukeH


        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.

UPDATE: This answer is far more efficient and should be used for lists of non-trivial size.

like image 41
Jake Avatar answered Sep 19 '22 05:09

Jake