溫馨提示×

c# sorteddictionary怎樣創建

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

在C#中,SortedDictionary是一個基于紅黑樹實現的鍵值對集合,它可以保持鍵的順序。要創建一個SortedDictionary,你需要使用SortedDictionary<TKey, TValue>類,并為其提供一個比較器(如果需要的話)。以下是一個簡單的示例:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // 創建一個SortedDictionary,鍵和值都是整數
        SortedDictionary<int, int> sortedDictionary = new SortedDictionary<int, int>();

        // 添加鍵值對
        sortedDictionary.Add(3, 30);
        sortedDictionary.Add(1, 10);
        sortedDictionary.Add(2, 20);

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

在這個示例中,我們創建了一個SortedDictionary<int, int>對象,并添加了三個鍵值對。然后,我們遍歷SortedDictionary并輸出每個鍵值對。

如果你需要根據自定義對象創建SortedDictionary,你需要實現IComparer<TKey>接口并提供一個比較器。例如:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // 創建一個SortedDictionary,鍵和值都是自定義對象
        SortedDictionary<MyObject, int> sortedDictionary = new SortedDictionary<MyObject, int>(new MyObjectComparer());

        // 添加鍵值對
        sortedDictionary.Add(new MyObject(3, "three"), 30);
        sortedDictionary.Add(new MyObject(1, "one"), 10);
        sortedDictionary.Add(new MyObject(2, "two"), 20);

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

class MyObject
{
    public int Id { get; set; }
    public string Name { get; set; }

    public MyObject(int id, string name)
    {
        Id = id;
        Name = name;
    }
}

class MyObjectComparer : IComparer<MyObject>
{
    public int Compare(MyObject x, MyObject y)
    {
        // 根據Id進行比較
        return x.Id.CompareTo(y.Id);
    }
}

在這個示例中,我們創建了一個SortedDictionary<MyObject, int>對象,并使用自定義的比較器MyObjectComparerMyObject實例進行排序。

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