Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List to Dictionary with incremental keys in one line LINQ statement

I have this list:

var items = new List<string>() { "Hello", "I am a value", "Bye" };

I want it to convert it to a dictionary with the following structure:

var dic = new Dictionary<int, string>()
{
     { 1, "Hello" },
     { 2, "I am a value" },
     { 3, "Bye" }
};

As you can see, the dictionary keys are just incremental values, but they should also reflect the positions of each element in the list.

I am looking for a one-line LINQ statement. Something like this:

var dic = items.ToDictionary(i => **Specify incremental key or get element index**, i => i);
like image 956
Matias Cicero Avatar asked Jul 27 '15 13:07

Matias Cicero


2 Answers

You can do that by using the overload of Enumerable.Select which passes the index of the element:

var dic = items.Select((val, index) => new { Index = index, Value = val})
               .ToDictionary(i => i.Index, i => i.Value);
like image 197
Yuval Itzchakov Avatar answered Oct 23 '22 00:10

Yuval Itzchakov


static void Main(string[] args)
{
    var items = new List<string>() { "Hello", "I am a value", "Bye" };
    int i = 1;
    var dict = items.ToDictionary(A => i++, A => A);

    foreach (var v in dict)
    {
        Console.WriteLine(v.Key + "   " + v.Value);
    }

    Console.ReadLine();    
}

Output

1   Hello
2   I am a value
3   Bye

EDIT: Out of curosity i did a performance test with a list of 3 million strings.

1st Place: Simple For loop to add items to a dictionary using the loop count as the key value. (Time: 00:00:00.2494029)

2nd Place: This answer using a integer variable outside of LINQ. Time(00:00:00.2931745)

3rd Place: Yuval Itzchakov's Answer doing it all on a single line. Time (00:00:00.7308006)

like image 43
CathalMF Avatar answered Oct 23 '22 01:10

CathalMF