tes*_*der 14 .net c# linq dictionary
我有List<String>,我需要将它转换为Dictionary<int,String>自动生成Key,是否有任何最短的方法来完成它?我试过了:
var dictionary = new Dictionary<int, String>();
int index = 0;
list.ForEach(x=>{
definitions.Add(index, x);
index++;
});
Run Code Online (Sandbox Code Playgroud)
但我认为这是肮脏的方式.
L.B*_*L.B 54
var dict = list.Select((s, i) => new { s, i }).ToDictionary(x => x.i, x => x.s);
Run Code Online (Sandbox Code Playgroud)
小智 15
我发现这是最整洁的
int index = 0;
var dictionary = myList.ToDictionary(item => index++);
Run Code Online (Sandbox Code Playgroud)
在我看来,你所拥有的比 Linq 方式更具可读性(而且作为奖励,它碰巧更有效):
foreach(var item in list)
dictionary[index++] = item;
Run Code Online (Sandbox Code Playgroud)