便宜VPS主机精选
提供服务器主机评测信息

如何在C#中使用SortedDictionary进行高效遍历

在C#中,SortedDictionary是一个有序字典,它根据键的顺序存储和遍历元素。要遍历SortedDictionary,您可以使用以下方法:

  1. 使用foreach循环遍历键值对:
SortedDictionary<TKey, TValue> sortedDictionary = new SortedDictionary<TKey, TValue>();

// 添加一些元素
sortedDictionary.Add("apple", 1);
sortedDictionary.Add("banana", 2);
sortedDictionary.Add("orange", 3);

// 使用foreach循环遍历键值对
foreach (KeyValuePair<TKey, TValue> entry in sortedDictionary)
{
    Console.WriteLine($"Key: {entry.Key}, Value: {entry.Value}");
}
  1. 使用迭代器遍历键值对:
SortedDictionary<TKey, TValue> sortedDictionary = new SortedDictionary<TKey, TValue>();

// 添加一些元素
sortedDictionary.Add("apple", 1);
sortedDictionary.Add("banana", 2);
sortedDictionary.Add("orange", 3);

// 使用迭代器遍历键值对
IEnumerator<KeyValuePair<TKey, TValue>> iterator = sortedDictionary.GetEnumerator();
while (iterator.MoveNext())
{
    KeyValuePair<TKey, TValue> entry = iterator.Current;
    Console.WriteLine($"Key: {entry.Key}, Value: {entry.Value}");
}

在这两种方法中,您都可以看到SortedDictionary中的元素按照键的顺序进行遍历。

未经允许不得转载:便宜VPS测评 » 如何在C#中使用SortedDictionary进行高效遍历