Reputation: 7385
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
Reputation: 419
I find this to be the neatest
int index = 0;
var dictionary = myList.ToDictionary(item => index++);
Upvotes: 19
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
Reputation: 56162
Use:
var dict = list.Select((x, i) => new {x, i})
.ToDictionary(a => a.i, a => a.x);
Upvotes: 4
Reputation: 116118
var dict = list.Select((s, i) => new { s, i }).ToDictionary(x => x.i, x => x.s);
Upvotes: 80