在C#中,你可以使用IComparer
接口來實現自定義排序規則
首先,創建一個實現IComparer
接口的類,并實現Compare
方法。在這個例子中,我們將根據字符串的長度進行排序:
using System;
public class CustomStringComparer : IComparer<string>
{
public int Compare(string x, string y)
{
return x.Length.CompareTo(y.Length);
}
}
接下來,你可以使用這個自定義排序規則對集合進行排序。例如,對一個字符串數組進行排序:
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);
}
}
}
輸出結果將按照字符串長度進行排序:
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);
}
}
}
輸出結果同樣將按照字符串長度進行排序。