我有List<String>
,我需要将它转换为Dictionary<int,String>
与自动生成Key,是否有任何最短的方法来完成它?我试过了:
var dictionary = new Dictionary<int, String>();
int index = 0;
list.ForEach(x=>{
definitions.Add(index, x);
index++;
});
但我认为这是肮脏的方式。
var dict = list.Select((s, i) => new { s, i }).ToDictionary(x => x.i, x => x.s);
使用:
var dict = list.Select((x, i) => new {x, i})
.ToDictionary(a => a.i, a => a.x);
在我看来,你拥有的东西比Linq方式更具可读性(作为奖励,它恰好更有效率):
foreach(var item in list)
dictionary[index++] = item;
我发现这是最好的
int index = 0;
var dictionary = myList.ToDictionary(item => index++);