可以使用LINQ的ToList()方法将C#中的Dictionary转换为List,示例代码如下:
using System.Collections.Generic;
using System.Linq;
// 创建Dictionary
Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("apple", 1);
dict.Add("banana", 2);
dict.Add("orange", 3);
// 转换为List
List<KeyValuePair<string, int>> list = dict.ToList();
// 遍历输出List中的元素
foreach (KeyValuePair<string, int> kvp in list)
{
Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
其中,ToList()方法将Dictionary转换为List<KeyValuePair<string, int>>,即包含键值对的泛型列表。如果需要只获取键或者值的列表,可以使用LINQ的Select()方法进行投影,示例代码如下:
// 获取键的列表
List<string> keyList = dict.Select(x => x.Key).ToList();
// 获取值的列表
List<int> valueList = dict.Select(x => x.Value).ToList();