List 三种排序问题【int,string,实体类】
在我们的实际开发过程当中,有需要数据重新整理下,比如把这些数据,重新编排下序列,按小到大或者从高到低等等;
废话不多说,直接上代码;
1.int类型这种最简单,因为官方提供现成的,直接调用即可
List
list1.Add(5);
list1.Add(10);
list1.Add(1);
list1.Add(6);
list1.Add(0);
//list1.Sort((x, y) => x.CompareTo(y));//升序 官方默认
list1.Sort((x, y) => -x.CompareTo(y));//降序
foreach (var item in list1)
{
Debug.Log("值===>>>" + item);//输出:10,6,5,1,0
}
2. string类 对于字符串类型的调用
结果:把值解析成拼音字母,按照首个英文字母顺序升序排列,如果首字母相同,比较第二个的首字母,以此类推。
List
names.Sort();
foreach (var item in names)
{
Debug.Log("====>>>"+ item); //输出:牛二,牛逼,狗狗,狗肉,猫,老虎
}
3. 实体类,这个用的比较多点
<1>定义实体类
public class ItemTypePP
{
public int id { get; set; }
public string name { get; set; }
}
<2>定义根据Id属性升序,降序排序的实体类 要继承【IComparer接口】
public class ItemTypeOrderById : IComparer
{
//方法体
public int Compare(ItemTypePP x, ItemTypePP y)
{
return x.id.CompareTo(y.id);//按id 升序
//return y.id.CompareTo(x.id);//按id 降序
}
}
<3>在Start()中
List
new ItemTypePP() { id = 5, name = "小霞" },
new ItemTypePP() { id = 0, name = "小红" },
new ItemTypePP() { id = -1, name = "jjjjj" },
new ItemTypePP() { id = 100, name = "dsafdsa" },
new ItemTypePP() { id = 10, name = "yyyyyy" }
};
// 在调用Sort()方法的时候,
list1.Sort(new ItemTypeOrderById());
foreach (var item in list1)
{
Debug.Log(item.id + "\t" + item.name);
}
输出结果: