1. 程式人生 > >List.Sort 排序

List.Sort 排序

//資料類實現IComparable介面
public class Item : IComparable
{
    public string name;
    public float price;

    //先根據name排序,如果name相同則根據price排序
    public int CompareTo(object obj)
    {
        Item target = obj as Item;
        int ret = 0;
        ret = this.name.CompareTo(target.name);
        if (ret == 0)
            ret = this.price.CompareTo(target.price);

        return ret;
    }
}

public class ListSort : MonoBehaviour 
{
    private List items = new List();

	void Start () {

        Item item1 = new Item();
        Item item2 = new Item();
        Item item3 = new Item();

        item1.name = "A";
        item1.price = 10;
        item2.name = "B";
        item2.price = 20;
        item3.name = "C";
        item3.price = 8;

        items.Add(item1);
        items.Add(item2);
        items.Add(item3);
    }

    void OnGUI()
    {
        if(GUILayout.Button("AA"))
        {
            //items.Sort();//如果資料類實現了IComparable介面則會自動呼叫內部的CompareTo函式進行排序
            //items.Sort(OnCompareTo);//如何資料類沒有繼承IComparable介面則可以通過此方法進行排序
        }

        if(GUILayout.Button("BB"))
        {
            for (int i = 0; i < items.Count; i++)
            {
                Debug.Log(items[i].name + "," + items[i].price);
            }
        }
    }
    
    //在呼叫items.Sort(OnCompareTo)方法是引數會自動傳進來
    //先根據name排序,如果name相同則根據price排序
    private int OnCompareTo(Item left,Item right)
    {
        int ret = 0;
        ret = left.name.CompareTo(right.name);
        if (ret == 0)
            ret = left.price.CompareTo(right.price);

        return ret;
    }
}