使用索引将List <string>选择为Dictionary

c0r*_*0rd 9 c# dictionary list

我有一个清单

List<string> sList = new List<string>() { "a","b","c"};
Run Code Online (Sandbox Code Playgroud)

目前我正在选择以下结构为字典:

//(1,a)(2,b)(3,c)
Dictionary<int, string> dResult = new Dictionary<int, string>();
for(int i=0;i< sList.Count;i++)
{
    dResult.Add(i, sList[i]);
}
Run Code Online (Sandbox Code Playgroud)

但是对于Linq,我看到了一些更苗条的方式 ToDictionary((x,index) =>

如何在一行内解决正确的语法或如何解决?

Tim*_*ter 15

您可以使用该Select索引的重载来填充匿名类型:

Dictionary<int, string> dResult = sList
    .Select((s, index) => new { s, index })
    .ToDictionary(x => x.index, x => x.s);
Run Code Online (Sandbox Code Playgroud)

这与您的代码所做的相同.如果你想要你已评论的结果:),(1,a)(2,b)(3,c)你必须添加+1 ToDictionary(x => x.index+1, x => x.s).


Jon*_*eet 8

没有ToDictionary方法可以在一次调用中提供这个,因为没有提供索引的Select重载,但是您可以使用接受以下内容的重载Func<T, int, TResult>:

var dictionary = list.Select((value, index) => new { value, index })
                     .ToDictionary(pair => pair.index, pair => pair.value);
Run Code Online (Sandbox Code Playgroud)

或者在C#7中,避免使用以下方法创建一堆堆分配的对象ValueTuple:

var dictionary = list.Select((v, i) => (value: v, index: i))
                     .ToDictionary(pair => pair.index, pair => pair.value);
Run Code Online (Sandbox Code Playgroud)

从C#7.1点发布开始,您可以使用推断的ValueTuple文字表达式:

var dictionary = list.Select((value, index) => (value, index))
                     .ToDictionary(pair => pair.index, pair => pair.value);
Run Code Online (Sandbox Code Playgroud)

(如Tim所述,您需要将索引调整为1才能获得原始请求的输出.)