C# 中的泛型排序器[二]
先直接上代码
using UnityEngine; using System.Collections; using System.Collections.Generic; public class GenericSortTest : MonoBehaviour { // Use this for initialization void Start () { List<ItemInfo> list = GetList(); list.Sort(SortCompar); for (int i = 0; i < list.Count; i++) { Debug.Log("id="+list[i].id+" name="+list[i].name+" price="+list[i].price); }
//一句话删除价格在30以下的
list.RemoveAll((o)=>o.price<30?true:false);
}
private int SortCompar(ItemInfo a,ItemInfo b) { //return a.id - b.id;//按id升序 //return b.id - a.id;//按id降序 //return a.price - b.price;//按价格升序 return b.price - a.price;//按价格降序 } public List<ItemInfo> GetList() { List<ItemInfo> flag = new List<ItemInfo>(); flag.Add(new ItemInfo() { id = 1, name = "a", price = 10 }); flag.Add(new ItemInfo() { id = 2, name = "b", price = 30 }); flag.Add(new ItemInfo() { id = 5, name = "c", price = 50 }); flag.Add(new ItemInfo() { id = 3, name = "d", price = 5 }); flag.Add(new ItemInfo() { id = 4, name = "e", price = 1 }); return flag; } } public class ItemInfo { public int id; public string name; public int price; }
这里是用U3D写的,有些特有类在C#里是没有的,如果只用C#的同学需要注意。
list.RemoveAll(System.Predicate<T>)传入其中的委托原型和System.Func<T,TR>是相同的,只是名字不同.
list.RemoveAll(System.Comparison<in T>)传入其中的委托原型和System.Func<TX,TY,int>是相同的,只是名字不同.这个初一看,还很难理解为什么System.Comparison<in T>看起来只是传入了一个参数,但是实际对应的委托原型却是两个参数,这个只有靠记着了,而且是通过返回的数字值的正负来判断排序方式,比较抽象.
另外再举个例子
Asm.Sort ((Data mx,Data my)=> //该方法实现的是将Asm由大到小的排序 { if (mx.mb > my.mb) return -1; //返回-1表示mx被认定排序值小于my,所以排在前面 else if (mx.mb < my.mb) return 1; //返回1 表示mx被认定排序值大于my,所以排在后面. else return 0; });
end

浙公网安备 33010602011771号