溫馨提示×

c# set集合 能自定義排序嗎

c#
小樊
120
2024-12-04 04:28:47
欄目: 編程語言

是的,在C#中,您可以使用SortedSet<T>類來自定義排序。SortedSet<T>是一個有序集合,它會根據元素的自然順序或者您提供的比較器(IComparer<T>)進行排序。

以下是一個使用SortedSet<T>并自定義排序的示例:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // 使用默認比較器(按自然順序排序)創建 SortedSet
        SortedSet<int> defaultSortedSet = new SortedSet<int>();
        defaultSortedSet.Add(5);
        defaultSortedSet.Add(3);
        defaultSortedSet.Add(8);
        defaultSortedSet.Add(1);

        Console.WriteLine("默認排序:");
        foreach (int item in defaultSortedSet)
        {
            Console.WriteLine(item);
        }

        // 使用自定義比較器創建 SortedSet
        SortedSet<int> customSortedSet = new SortedSet<int>(new MyComparer());
        customSortedSet.Add(5);
        customSortedSet.Add(3);
        customSortedSet.Add(8);
        customSortedSet.Add(1);

        Console.WriteLine("\n自定義排序:");
        foreach (int item in customSortedSet)
        {
            Console.WriteLine(item);
        }
    }
}

// 自定義比較器實現 IComparer<int> 接口
class MyComparer : IComparer<int>
{
    public int Compare(int x, int y)
    {
        return y - x; // 降序排序
    }
}

在這個示例中,我們首先使用默認的比較器(按自然順序排序)創建了一個SortedSet<int>。然后,我們創建了一個自定義比較器MyComparer,它實現了IComparer<int>接口,并在Compare方法中返回y - x,以實現降序排序。最后,我們使用自定義比較器創建了一個新的SortedSet<int>,并添加了相同的元素。輸出結果將顯示默認排序和自定義排序的結果。

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