c# - 如何将 List<String> 转换为 Dictionary<int,String>

标签 c# .net 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++;
});

但我认为这是肮脏的方式。

最佳答案

var dict = list.Select((s, i) => new { s, i }).ToDictionary(x => x.i, x => x.s);

关于c# - 如何将 List<String> 转换为 Dictionary<int,String>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13718305/

相关文章:

c# - 在 Linq 谓词中,编译器会优化对 Enumerable.Min() 的 "scalar"调用还是会为每个项目调用它?

c# - DbContext.Set() 上的 LINQ

c# - 为什么 2.0 之后的 C# 没有 ISO 或 ECMA 标准化?

c# - 如何将 linq 查询返回到单个对象

c# - 子控件中的 `DesignMode` 设置不正确?

.net - Visual Studio 是否支持编辑 Robots.txt?

c# - 如何转换日期时间?到日期时间

c# - 局部变量实际上在 CLR 中分配在哪里?

c# - 从网络浏览器中选择下拉选项

c# - 为 IQueryable<T> 生成表达式