//数据类实现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;
}
}
List.Sort 排序
最新推荐文章于 2022-03-30 00:09:47 发布