Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert List<String> to Dictionary<int,String>

Tags:

I have List<String>, i need to convert it to Dictionary<int,String> with auto generation of Key, is any shortest way to accomplish that? I have tried:

    var dictionary = new Dictionary<int, String>();     int index = 0;     list.ForEach(x=>{       definitions.Add(index, x);       index++; }); 

but i think it is dirty way.

like image 564
testCoder Avatar asked Dec 05 '12 07:12

testCoder


People also ask

How do I convert a list to a dictionary in python?

Since python dictionary is unordered, the output can be in any order. To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.

Can we convert list to dictionary in C#?

Convert List to Dictionary Using the Non-Linq Method in C# We can also convert a list to a dictionary in a non-LINQ way using a loop. It is advised to use the non-LINQ method because it has improved performance, but we can use either method according to our preferences.


2 Answers

var dict = list.Select((s, i) => new { s, i }).ToDictionary(x => x.i, x => x.s); 
like image 123
L.B Avatar answered Sep 27 '22 21:09

L.B


I find this to be the neatest

int index = 0; var dictionary = myList.ToDictionary(item => index++); 
like image 28
Johan Sonesson Avatar answered Sep 27 '22 21:09

Johan Sonesson