温馨提示×

c#中dictionary怎么改成list

c#
小亿
150
2024-02-05 10:40:36
栏目: 编程语言

要将C#中的Dictionary改成List,可以使用Dictionary的Keys和Values属性。可以使用Keys属性获得Dictionary中的所有键,并使用Values属性获得所有的值。然后使用List的构造函数将键和值转换为List。以下是一个示例:

Dictionary<string, int> myDictionary = new Dictionary<string, int>();
myDictionary.Add("Apple", 1);
myDictionary.Add("Banana", 2);
myDictionary.Add("Orange", 3);

List<string> keys = new List<string>(myDictionary.Keys);
List<int> values = new List<int>(myDictionary.Values);

Console.WriteLine("Keys:");
foreach (string key in keys)
{
    Console.WriteLine(key);
}

Console.WriteLine("Values:");
foreach (int value in values)
{
    Console.WriteLine(value);
}

输出:

Keys:
Apple
Banana
Orange
Values:
1
2
3

在上面的示例中,我们首先定义了一个Dictionary对象,并向其添加了一些键值对。然后使用Keys属性将键转换为List,并使用Values属性将值转换为List。最后使用foreach循环打印出List中的元素。

0