温馨提示×

c#集合如何排序元素

c#
小樊
105
2024-11-20 13:19:34
栏目: 编程语言

在C#中,可以使用List类或Dictionary类中的方法对集合进行排序。

如果要对List中的元素进行排序,可以使用List类的Sort()方法。例如:

List<int> myList = new List<int> { 3, 1, 4, 1, 5, 9 }; myList.Sort(); foreach (int item in myList) { Console.WriteLine(item); } 

输出结果为:

1 1 3 4 5 9 

如果要对Dictionary中的键或值进行排序,可以使用Dictionary类的Keys或Values属性,然后使用List类的Sort()方法。例如,要对Dictionary中的键进行排序,可以这样做:

Dictionary<string, int> myDict = new Dictionary<string, int> { { "apple", 3 }, { "banana", 1 }, { "orange", 4 } }; List<string> sortedKeys = new List<string>(myDict.Keys); sortedKeys.Sort(); foreach (string key in sortedKeys) { Console.WriteLine(key + ": " + myDict[key]); } 

输出结果为:

apple: 3 banana: 1 orange: 4 

0