如何转换List 到字典

问题描述 投票:13回答:4

我有List<String>,我需要将它转换为Dictionary<int,String>与自动生成Key,是否有任何最短的方法来完成它?我试过了:

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

但我认为这是肮脏的方式。

c# .net linq dictionary
4个回答
50
投票
var dict = list.Select((s, i) => new { s, i }).ToDictionary(x => x.i, x => x.s);

4
投票

使用:

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

4
投票

在我看来,你拥有的东西比Linq方式更具可读性(作为奖励,它恰好更有效率):

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

1
投票

我发现这是最好的

int index = 0;
var dictionary = myList.ToDictionary(item => index++);
© www.soinside.com 2019 - 2024. All rights reserved.