擴展:
在 C# 语言中提供了 IComparer 和 IComparable 接口比较集合中的对象值,主要用于对集合中的元素排序。
IComparer 接口用于在一个单独的类中实现,用于比较任意两个对象。
IComparable 接口用于在要比较的对象的类中实现,可以比较任意两个对象。
//IComparer 接口
using System;
using System.Collections.Generic;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
List<Hero> heroes = new List<Hero>();
heroes.Add(new Hero("male", 1));
heroes.Add(new Hero("male", 2));
heroes.Add(new Hero("male", 3));
heroes.Add(new Hero("female", 1));
heroes.Add(new Hero("female", 2));
heroes.Add(new Hero("female", 3));
heroes.Sort(new HeroSort()); //實現Comparer<T>接口,從而實現對自定義類進行自定義排序
foreach(var a in heroes)
{
Console.WriteLine(a.Gender+"----"+a.Strength);
}
Hero hero1 = new Hero("male", 1); //也可以對任意兩個Hero類進行比較
Hero hero2 = new Hero("male", 1);
HeroSort heroSort = new HeroSort();
int i=heroSort.Compare(hero1, hero2);
Console.WriteLine(i);
Console.ReadKey();
}
}
/// <summary>
///在一个单独的类中实现IComparer
/// 此處的排序規則:先排性別,後排武力值,男性在前,武力值大的在前
/// </summary>
class HeroSort : IComparer<Hero>
{
public int Compare(Hero x, Hero y)
{
if(x.Gender != y.Gender)
{
if (x.Gender == "male")
{
return -1;
}
else
{
return 1;
}
}
else
{
return -x.Strength.CompareTo(y.Strength);
}
}
}
class Hero
{
public string Gender { get; set; }
public int Strength { get; set; }
public Hero(string gender,int strength)
{
this.Gender = gender;
this.Strength = strength;
}
}
}
//IComparable接口
using System;
using System.Collections.Generic;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
List<Hero> heroes = new List<Hero>();
heroes.Add(new Hero("male", 1));
heroes.Add(new Hero("male", 2));
heroes.Add(new Hero("male", 3));
heroes.Add(new Hero("female", 1));
heroes.Add(new Hero("female", 2));
heroes.Add(new Hero("female", 3));
heroes.Sort(); //要想實現此處自定義類Hero排序(自定義排序),需要在此類中實現接口IComparable(最好是泛型接口,這樣就不會頻繁的裝拆箱),不然此方法無法執行
foreach (var a in heroes)
{
Console.WriteLine(a.Gender + "----" + a.Strength);
}
Hero hero1 = new Hero("male", 1); //也可以對任意兩個Hero類進行比較
Hero hero2 = new Hero("male", 1);
int i= hero1.CompareTo(hero2);
Console.WriteLine(i);
Console.ReadKey();
}
}
/// <summary>
///與IComparer在一个单独的类中实现不同,IComparable需要在要比較的類中實現
/// 排序規則:先排性別,後排武力值,男性在前,武力值大的在前
/// </summary>
class Hero:IComparable<Hero>
{
public string Gender { get; set; }
public int Strength { get; set; }
public Hero(string gender, int strength)
{
this.Gender = gender;
this.Strength = strength;
}
public int CompareTo(Hero other)
{
if (this.Gender != other.Gender)
{
if (this.Gender == "male")
{
return -1;
}
else
{
return 1;
}
}
else
{
return -this.Strength.CompareTo(other.Strength);
}
}
}
}