testCoder
testCoder

Reputation: 7385

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

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.

Upvotes: 30

Views: 40645

Answers (4)

Johan Sonesson
Johan Sonesson

Reputation: 419

I find this to be the neatest

int index = 0;
var dictionary = myList.ToDictionary(item => index++);

Upvotes: 19

Eren Ers&#246;nmez
Eren Ers&#246;nmez

Reputation: 39085

In my opinion, what you have is more readable than the Linq way (and as a bonus, it happens to be more efficient):

foreach(var item in list)
    dictionary[index++] = item;

Upvotes: 6

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56162

Use:

var dict = list.Select((x, i) => new {x, i})
    .ToDictionary(a => a.i, a => a.x);

Upvotes: 4

L.B
L.B

Reputation: 116118

var dict = list.Select((s, i) => new { s, i }).ToDictionary(x => x.i, x => x.s);

Upvotes: 80

Related Questions