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

linq Distinct 去除重复数据

时间:2015-04-17 20:17:17      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:

转载:http://www.cnblogs.com/ldp615/archive/2011/08/01/distinct-entension.html

只可惜linq默认不支持.Distinct(p => p.ID);

试想如果能写成下面的样子,是不是更简单优雅:

var p1 = products.Distinct(p => p.ID);
var p2 = products.Distinct(p => p.Name);

 使用一个简单的 lambda 作为参数,也符合 Linq 一贯的风格。

 

扩展方法:

public static IEnumerable<T> Distinct<T, V>(this IEnumerable<T> source, Func<T, V> keySelector,
    IEqualityComparer<V> comparer = EqualityComparer<V>.Default)
{
    return source.Distinct(new CommonEqualityComparer<T, V>(keySelector, comparer));
}
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Linq;

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

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

    public CommonEqualityComparer(Func<T, V> keySelector)
        : this(keySelector, EqualityComparer<V>.Default)
    {  }

    public bool Equals(T x, T y)
    {
        return comparer.Equals(keySelector(x), keySelector(y));
    }

    public int GetHashCode(T obj)
    {
        return comparer.GetHashCode(keySelector(obj));
    }
}

 

linq Distinct 去除重复数据

标签:

原文地址:http://www.cnblogs.com/zfanlong1314/p/4435719.html

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