溫馨提示×

如何在C#中實現(xiàn)自定義排序規(guī)則

c#
小樊
81
2024-09-26 17:49:23
欄目: 編程語言

在C#中,你可以使用IComparer接口來實現(xiàn)自定義排序規(guī)則

首先,創(chuàng)建一個實現(xiàn)IComparer接口的類,并實現(xiàn)Compare方法。在這個例子中,我們將根據(jù)字符串的長度進行排序:

using System;

public class CustomStringComparer : IComparer<string>
{
    public int Compare(string x, string y)
    {
        return x.Length.CompareTo(y.Length);
    }
}

接下來,你可以使用這個自定義排序規(guī)則對集合進行排序。例如,對一個字符串?dāng)?shù)組進行排序:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        string[] words = { "apple", "banana", "cherry", "date", "fig", "grape" };

        CustomStringComparer comparer = new CustomStringComparer();

        Array.Sort(words, comparer);

        Console.WriteLine("Sorted words:");
        foreach (string word in words)
        {
            Console.WriteLine(word);
        }
    }
}

輸出結(jié)果將按照字符串長度進行排序:

Sorted words:
fig
apple
date
banana
grape
cherry

你還可以使用List<T>Sort方法對列表進行排序:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<string> words = new List<string> { "apple", "banana", "cherry", "date", "fig", "grape" };

        CustomStringComparer comparer = new CustomStringComparer();

        words.Sort(comparer);

        Console.WriteLine("Sorted words:");
        foreach (string word in words)
        {
            Console.WriteLine(word);
        }
    }
}

輸出結(jié)果同樣將按照字符串長度進行排序。

0