C# 中的 ToDictionary 方法

csharpprogrammingserver side programming更新于 2025/9/22 20:22:17

ToDictionary 方法是 C# 中的一个扩展方法,用于将集合转换为 Dictionary。

首先,创建一个字符串数组 −

string[] str = new string[] {"Car", "Bus", "Bicycle"};

现在,使用 Dictionary 方法将集合转换为 Dictionary −

str.ToDictionary(item => item, item => true);

以下是完整代码 −

示例

using System;
using System.Collections.Generic;
using System.Linq;
类 Demo {
   static void Main() {
      string[] str = new string[] {&"Car&", &"Bus&", &"Bicycle&"};
      // ToDictionary 下的键和值
      var d = str.ToDictionary(item => item, item => true);
      foreach (var ele in d) {
         Console.WriteLine("{0}, {1}", ele.Key, ele.Value);
      }
   }
}

输出

Car, True
Bus, True
Bicycle, True

相关文章