List<T>.Sort() 排序的用法
2016-07-07 17:31
411 查看
List<T> 可以通过 .Sort()进行排序,但是当 T 对象为自定义类型时(比如自定义模型),就需要 IComparable接口重写其中的方法来实现,实现代码如下:
如果不继续IComparable接口,也可以直接在 .Sort()方法里面写,代码如下:
按照功能排序:List<T> < IList<T> < ICollection<T> < IEnumerable<T>
按照性能排序:IEnumerable<T> < ICollection<T> < IList<T> < List<T>
class Program { static Func<Model, int> where = a => a.id; static Func<Model, bool> wherelambda = a => a.id < 3; static void Main(string[] a) { List<Model> result = GetData().ToList(); result.Sort(); //排序 } /// <summary> /// 拼装数据 /// </summary> /// <returns></returns> #region public static IList<Model> GetData() { IList<Model> list = new List<Model>(); for (int i = 0; i <= 10; i++) { Model model = new Model(); model.id = i; model.Name = "名字" + i; model.Email = string.Format("12345@QQ{0}.com.cn", i); list.Add(model); } return list; } #endregion } /// <summary> /// 自定义模型 一定要继承 IComparable<T>接口 /// </summary> public class Model : IComparable<Model> { public int id { get; set; } private int Sex { get; set; } public string Name { get; set; } public DateTime? BirthDate { get; set; } public string Email { get; set; } public string Phone { get; set; } public int CompareTo(Model model) { if (model.id == id && model.Name.Equals(Name)) return 0; else { if (id > model.id) { return -1; } if (Name.CompareTo(model.Name) > 0) { return -1; } else return 1; } } }
如果不继续IComparable接口,也可以直接在 .Sort()方法里面写,代码如下:
class Program { static Func<Model, int> where = a => a.id; static Func<Model, bool> wherelambda = a => a.id < 3; static void Main(string[] a) { List<Model> result = GetData().ToList(); result.Sort((a,b)=>{ if (b.id == a.id && b.Name.Equals(a.Name)) return 0; else { if (a.id > b.id) { return -1; } if (a.Name.CompareTo(b.Name) > 0) { return -1; } else return 1; } }); //排序 }
按照功能排序:List<T> < IList<T> < ICollection<T> < IEnumerable<T>
按照性能排序:IEnumerable<T> < ICollection<T> < IList<T> < List<T>
相关文章推荐
- PHP篇之HTML5
- NDK/JNI Develop guide(6) access the instance variables and static variables
- 一分钟教你知道乐观锁和悲观锁的区别
- 弹出、收缩的菜单
- ios在2g/3g/4g网络下的抓包方法
- linux 内核库函数 【转】
- bashrc
- Sla子分类账表结构
- 关于socket长连接的心跳包
- the directory item limit is exceed: limit=1048576问题的解决
- 判断字符串中符号是否成对出现
- java操作mongoDB
- PHP利用CURL方法模拟POST提交数据并获得返回值的小细节
- L2-001. 紧急救援
- final常量
- WARN: Establishing SSL connection without server's identity verification is not recommended.
- Web app root system property already set to different value: 'webapp.root'
- 敏捷开发之Scrum扫盲篇
- Eclipse RCP实用小技巧
- 在使用angularjs时遇到的几个问题