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

Distinct<TSource>(IEqualityComparer<TSource> comparer) 根据列名来Distinct

时间:2014-11-21 23:07:47      阅读:263      评论:0      收藏:0      [点我收藏+]

标签:io   ar   on   ef   as   new   text   return   class   

1. DistinctEqualityComparer.cs

public class DistinctEqualityComparer<T, V> : IEqualityComparer<T>
    {
        private Func<T, V> keySelector;

        public DistinctEqualityComparer(Func<T, V> keySelector)
        {
            this.keySelector = keySelector;
        }

        public bool Equals(T x, T y)
        {
            return EqualityComparer<V>.Default.Equals(keySelector(x), keySelector(y));
        }

        public int GetHashCode(T obj)
        {
            return EqualityComparer<V>.Default.GetHashCode(keySelector(obj));
        }
    }

2. DistinctExtensions.cs

public static class DistinctExtensions
    {
        public static IEnumerable<T> Distinct<T, V>(this IEnumerable<T> source, Func<T, V> keySelector)
        {
            return source.Distinct(new DistinctEqualityComparer<T, V>(keySelector));
        }
    }

3. Program.cs

class Program
    {
        static void Main(string[] args)
        {
            List<Person> personList = new List<Person>(){
                new Person(){Id = 1, Name = "Steven"},
                new Person(){Id = 2, Name = "Steven"},
                new Person(){Id = 3, Name = "Steven"},
                new Person(){Id = 3, Name = "Steven"},
            };

            List<Person> delegateList = personList.Distinct(x => x.Id).ToList();
        }
    }

Distinct<TSource>(IEqualityComparer<TSource> comparer) 根据列名来Distinct

标签:io   ar   on   ef   as   new   text   return   class   

原文地址:http://www.cnblogs.com/zisezhixin/p/4113930.html

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