首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 陣列排序與物件比較大小完整指南

     編輯:關於C語言

基礎:基本類型陣列排序


int[] arr = { 2, 3, 6, 1, 4, 5 };
Array.Sort(arr);
Array.ForEach(arr, i => Console.WriteLine(i)); // 1 2 3 4 5 6

自訂類別排序:必須實作 IComparable


public class Student : IComparable
{
    public int Age { get; set; }
    public string Name { get; set; }
    public int Score { get; set; }

    public int CompareTo(object obj)
    {
        if (obj is Student other) return Age.CompareTo(other.Age);
        return 1;
    }
}

直接 Array.Sort(students) 即可依 Age 排序。若未實作 IComparable,執行時拋出 InvalidOperationException。

多重排序準則:IComparer<T> 策略模式


public class StudentScoreComparer : IComparer
{
    public int Compare(Student x, Student y) => x.Score.CompareTo(y.Score);
}

呼叫:Array.Sort(students, new StudentScoreComparer()); 依 Score 排序。

輕量彈性:Comparison<T> 委派 + Lambda


Array.Sort(students, (s1, s2) => s1.Score.CompareTo(s2.Score));

無需額外類別,適合一次性或簡單排序邏輯。

三大比較介面/委派總結

介面/委派用途特點
IComparable類別內建預設比較單一排序規則,型別自身實作
IComparable<T>強型別版本避免裝箱,建議優先實作
IComparer<T>外部比較器 (策略模式)多重排序規則、分離關注點
Comparison<T>委派形式比較Lambda/匿名方法,輕量彈性

完整範例程式碼


using System;
using System.Collections.Generic;

namespace SortingInCSharp
{
    class Program
    {
        public class Student : IComparable
        {
            public int Age { get; set; }
            public string Name { get; set; }
            public int Score { get; set; }
            public int CompareTo(object obj) => obj is Student s ? Age.CompareTo(s.Age) : 1;
        }

        public class StudentScoreComparer : IComparer
        {
            public int Compare(Student x, Student y) => x.Score.CompareTo(y.Score);
        }

        static void Main()
        {
            var students = new[]
            {
                new Student { Age = 10, Name = "張三", Score = 70 },
                new Student { Age = 12, Name = "李四", Score = 97 },
                new Student { Age = 11, Name = "王五", Score = 80 },
                new Student { Age = 9,  Name = "趙六", Score = 66 },
                new Student { Age = 12, Name = "司馬", Score = 90 }
            };

            Console.WriteLine("--- 預設排序 (Age) ---");
            Array.Sort(students);
            Print(students);

            Console.WriteLine("--- 依 Score 排序 (IComparer) ---");
            Array.Sort(students, new StudentScoreComparer());
            Print(students);

            Console.WriteLine("--- 依 Score 排序 (Lambda) ---");
            Array.Sort(students, (s1, s2) => s1.Score.CompareTo(s2.Score));
            Print(students);

            Console.Read();
        }
        static void Print(Student[] arr) => Array.ForEach(arr, s => Console.WriteLine($"{s.Name}{s.Age,2}歲,分數{s.Score,3}"));
    }
}

原文連結

https://www.cnblogs.com/yukaizhao/archive/2011/08/19/csharp-compare.html

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved