gpt4 book ai didi

c# - 使用索引选择 List 到 Dictionary

转载 作者:太空狗 更新时间:2023-10-29 17:30:02 25 4
gpt4 key购买 nike

我有一个列表

List<string> sList = new List<string>() { "a","b","c"};

目前我正在将其选入具有以下结构的字典中:

//(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]);
}

但是对于 Linq,我看到了一些更简洁的方法,比如 ToDictionary((x,index) =>

正确的语法是怎样的,或者如何在一行中解决这个问题?

最佳答案

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

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

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

关于c# - 使用索引选择 List<string> 到 Dictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39386251/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com