溫馨提示×

c# sorteddictionary如何遍歷

c#
小樊
153
2024-11-23 01:17:04
欄目: 編程語言

在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中的元素按照鍵的順序進行遍歷。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女