独自クラスの配列やListをソートする
3種類の実装方法を示します。
1) ソートしたい対象のクラスに、IComparableインターフェースのCompareToメソッドを実装する方法
2) ラムダ式を使う方法
3) 独自の比較関数を定義する方法
下記の実装例を参照してください。
public class SortTest
{
private List shoppingList;
public SortTest()
{
shoppingList = new List();
shoppingList.Add(new Buy("milk", 320, 1));
shoppingList.Add(new Buy("egg", 262, 5));
shoppingList.Add(new Buy("tofu", 374, 2));
}
public void Sort()
{
shoppingList.Sort(); // IComparableによるソート
shoppingList.Sort((a, b) => a.name.CompareTo(b.name)); // ラムダ式によるソート
shoppingList.Sort(CompareByAmount); // 独自比較関数によるソート
}
// 独自の比較関数。個数の順でソートする
private static int CompareByAmount(Buy a, Buy b)
{
return a.amount.CompareTo(b.amount);
}
}
public class Buy : IComparable
{
public string name { get; set; }
public int price { get; set; }
public int amount { get; set; }
public Buy(string _name, int _price, int _amount)
{
this.name = _name;
this.price = _price;
this.amount = _amount;
}
// IComparableのメソッド。金額×個数の順でソートする
public int CompareTo(object obj)
{
int thisSum = this.price * this.amount;
int otherSum = ((Buy)obj).price * ((Buy)obj).amount;
return thisSum.CompareTo(otherSum);
}
}