C# dictionary冒泡排序
时间: 2023-11-20 22:58:24 浏览: 47
很抱歉,C#中的Dictionary是一种无序的数据结构,因此不存在对其进行排序的操作。如果您需要对键值对进行排序,可以考虑使用SortedDictionary或者将键值对转换为List进行排序。
以下是将键值对转换为List进行排序的示例代码:
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("apple", 3);
dict.Add("banana", 2);
dict.Add("orange", 4);
dict.Add("pear", 1);
List<KeyValuePair<string, int>> list = dict.ToList();
// 按照键值升序排序
list.Sort((pair1, pair2) => pair1.Value.CompareTo(pair2.Value));
foreach (KeyValuePair<string, int> pair in list)
{
Console.WriteLine("{0}: {1}", pair.Key, pair.Value);
}
}
}
```