集合 List<T> 排重方法 Distinct()
2013-10-31 11:41
274 查看
class ListDistinctDemo { static void Main(string[] args) { List<Person> personList = new List<Person>(){ new Person(3),//重复数据 new Person(3), new Person(2), new Person(1) }; //使用匿名方法 List<Person> delegateList = personList.Distinct(new Compare<Person>( delegate(Person x, Person y) { if (null == x || null == y) return false; return x.ID == y.ID; })).ToList(); delegateList.ForEach(s => Console.WriteLine(s.ID)); //使用 Lambda 表达式 List<Person> lambdaList = personList.Distinct(new Compare<Person>( (x, y) => (null != x && null != y) && (x.ID == y.ID))).ToList(); lambdaList.ForEach(s => Console.WriteLine(s.ID)); //排序 personList.Sort((x, y) => x.ID.CompareTo(y.ID)); personList.ForEach(s => Console.WriteLine(s.ID)); } } public class Person { public int ID { get; set; } public string Name { get; set; } public Person(int id) { this.ID = id; } } public delegate bool EqualsComparer<T>(T x, T y); public class Compare<T> : IEqualityComparer<T> { private EqualsComparer<T> _equalsComparer; public Compare(EqualsComparer<T> equalsComparer) { this._equalsComparer = equalsComparer; } public bool Equals(T x, T y) { if (null != this._equalsComparer) return this._equalsComparer(x, y); else return false; } public int GetHashCode(T obj) { return obj.ToString().GetHashCode(); } }
相关文章推荐
- eclipse下的两个小问题
- 快速编译Delphi XE3 项目工程组
- 读取并解析一个文本文件处理流程:编码、InputStreamReader、BufferedReader
- 入住CSDN
- 一个PHP购物车类
- WdatePicker.js的使用方法 帮助文档 使用说明(时间控件)
- 文件拖动Drag & Drop 全解析
- 蓝屏 STOP:c0000218 {Registry File Failure}
- struts2 18拦截器详解(六)
- 例题第3章
- sql---应用
- python uwsgi 部署以及优化
- Gson- json转换的jar包工具-来自google
- Js与Java的基本数据类型
- S 串口编程 详解4 串口发送数据
- Oracle备份恢复arcgis数据问题
- github上传自己代码的使用步骤
- 学习WEB开发,从此我爱上了火狐的FireBug
- 从脚本中导入的存储过程脚本,注释没有了
- Openfire3.6JVM检测-win server版