溫馨提示×

c# sorteddictionary能排序嗎

c#
小樊
113
2024-11-23 01:19:07
欄目: 編程語言

是的,SortedDictionary 是 C# 中的一個有序字典實現,它會根據鍵(Key)自動進行排序。SortedDictionarySystem.Collections.Generic 命名空間下的一個類,它繼承自 Dictionary 類。

以下是一個簡單的示例,展示了如何使用 SortedDictionary

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // 創建一個 SortedDictionary
        SortedDictionary<int, string> sortedDictionary = new SortedDictionary<int, string>();

        // 向 SortedDictionary 中添加鍵值對
        sortedDictionary.Add(3, "three");
        sortedDictionary.Add(1, "one");
        sortedDictionary.Add(2, "two");

        // 遍歷 SortedDictionary
        foreach (KeyValuePair<int, string> entry in sortedDictionary)
        {
            Console.WriteLine($"Key: {entry.Key}, Value: {entry.Value}");
        }
    }
}

輸出結果:

Key: 1, Value: one
Key: 2, Value: two
Key: 3, Value: three

從輸出結果可以看出,SortedDictionary 中的鍵值對已經按照鍵的升序排列。

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