c#中dictionary怎么改成list

avatar
作者
筋斗云
阅读量:0

要将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中的元素。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!