List的排序方法
1.对于数值类型的排序
public List<int> TestList=new List<int>();
void Start()
{
TestList.Add(9);
TestList.Add(7);
TestList.Add(2);
TestList.Add(12);
TestList.Add(1);
TestList.Sort();//从小到大
foreach (var item in TestList)
{
Debug.Log(item);
}
}
运行结果:
2.根据对象里的数据对list排序
public class Peopel
{
public string name;
public int age;
}
public List<Peopel> pe = new List<Peopel>();
void Start()
{
Peopel p1 = new Peopel()
{
name = "q",
age = 2
};
Peopel p2 = new Peopel()
{
name = "w",
age = 5
};
Peopel p3 = new Peopel()
{
name = "e",
age = 1
};
Peopel p4 = new Peopel()
{
name = "r",
age = 35
};
Peopel p5 = new Peopel()
{
name = "t",
age = 0
};
pe.Add(p1);
pe.Add(p2);
pe.Add(p3);
pe.Add(p4);
pe.Add(p5);
Paixu();
foreach (var item in pe)
{
Debug.Log(item.age);
}
}
//排序方法
void Paixu()
{
//排序的方法
//1.通过linq表达式 从小到大
pe.OrderBy(_ => _.age).ToList();
//2.通过linq表达式 从大到小
pe.OrderByDescending(_ => _.age).ToList();
//3.通过list自带的函数 从小到大
pe.Sort((pe, pe2) => pe.age.CompareTo(pe2.age));
//4.通过list自带的函数 从大到小
pe.Sort((pe, pe2) => pe2.age.CompareTo(pe.age));
}
运行结果(此图为从小到大的排序图):