C# 如何将 List<String> 转换为 Dictionary<int,String>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13718305/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert List<String> to Dictionary<int,String>
提问by testCoder
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:
我有List<String>,我需要将它转换为Dictionary<int,String>自动生成密钥,有什么最短的方法可以实现吗?我试过了:
var dictionary = new Dictionary<int, String>();
int index = 0;
list.ForEach(x=>{
definitions.Add(index, x);
index++;
});
but i think it is dirty way.
但我认为这是肮脏的方式。
采纳答案by L.B
var dict = list.Select((s, i) => new { s, i }).ToDictionary(x => x.i, x => x.s);
回答by Kirill Polishchuk
Use:
用:
var dict = list.Select((x, i) => new {x, i})
.ToDictionary(a => a.i, a => a.x);
回答by Eren Ers?nmez
In my opinion, what you have is more readable than the Linq way (and as a bonus, it happens to be more efficient):
在我看来,你所拥有的比 Linq 方式更具可读性(而且作为奖励,它碰巧更有效):
foreach(var item in list)
dictionary[index++] = item;
回答by Johan Sonesson
I find this to be the neatest
我发现这是最整洁的
int index = 0;
var dictionary = myList.ToDictionary(item => index++);

