码迷,mamicode.com
首页 > 其他好文 > 详细

List Distinct

时间:2015-09-07 19:32:34      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:

list集合的去重操作

代码

    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();
        }
    }

 

List Distinct

标签:

原文地址:http://www.cnblogs.com/xbblogs/p/4789706.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!