为何Linq的Distinct实在是不给力

 更新时间:2013年05月13日 17:56:07   作者:  
本篇文章对Linq的Distinct进行了详细的分析介绍,需要的朋友参考下
假设我们有一个类:Product

public class Product
{
    public string Id { get; set; }
    public string Name { get; set; }
}
Main函数如下:
static void Main()
{
    List<Product> products = new List<Product>()
    {
        new Product(){ Id="1", Name="n1"},
        new Product(){ Id="1", Name="n2"},
        new Product(){ Id="2", Name="n1"},
        new Product(){ Id="2", Name="n2"},
    };
    var distinctProduct = products.Distinct();
    Console.ReadLine();
}
可以看到distinctProduct 的结果是:

image

因为Distinct 默认比较的是Product对象的引用,所以返回4条数据。
那么如果我们希望返回Id唯一的product,那么该如何做呢?
 
Distinct方法还有另一个重载:
//通过使用指定的 System.Collections.Generic.IEqualityComparer<T> 对值进行比较
//返回序列中的非重复元素。
 public static IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> source,
IEqualityComparer<TSource> comparer);
该重载接收一个IEqualityComparer的参数。
假设要按Id来筛选,那么应该新建类ProductIdComparer 内容如下:
public class ProductIdComparer : IEqualityComparer<Product>
{
    public bool Equals(Product x, Product y)
    {
        if (x == null)
            return y == null;
        return x.Id == y.Id;
    }
    public int GetHashCode(Product obj)
    {
        if (obj == null)
            return 0;
        return obj.Id.GetHashCode();
    }
}
使用的时候,只需要
var distinctProduct = products.Distinct(new ProductIdComparer());
结果如下:

image

现在假设我们要 按照 Name来筛选重复呢?
很明显,需要再添加一个类ProductNameComparer.
那能不能使用泛型类呢??
新建类PropertyComparer<T> 继承IEqualityComparer<T> 内容如下:
public class PropertyComparer<T> : IEqualityComparer<T>
{
    private PropertyInfo _PropertyInfo;
    /// <summary>
    /// 通过propertyName 获取PropertyInfo对象   
    /// </summary>
    /// <param name="propertyName"></param>
    public PropertyComparer(string propertyName)
    {
        _PropertyInfo = typeof(T).GetProperty(propertyName,
        BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public);
        if (_PropertyInfo == null)
        {
            throw new ArgumentException(string.Format("{0} is not a property of type {1}.",
                propertyName, typeof(T)));
        }
    }
    #region IEqualityComparer<T> Members
    public bool Equals(T x, T y)
    {
        object xValue = _PropertyInfo.GetValue(x, null);
        object yValue = _PropertyInfo.GetValue(y, null);
        if (xValue == null)
            return yValue == null;
        return xValue.Equals(yValue);
    }
    public int GetHashCode(T obj)
    {
        object propertyValue = _PropertyInfo.GetValue(obj, null);
        if (propertyValue == null)
            return 0;
        else
            return propertyValue.GetHashCode();
    }
    #endregion
}

主要是重写的Equals 和GetHashCode 使用了属性的值比较。
使用的时候,只需要:
//var distinctProduct = products.Distinct(new PropertyComparer<Product>("Id"));
var distinctProduct = products.Distinct(new PropertyComparer<Product>("Name"));

结果如下:

image

为什么微软不提供PropertyEquality<T> 这个类呢?
按照上面的逻辑,这个类应该没有很复杂啊,细心的同学可以发现PropertyEquality 大量的使用了反射。每次获取属性的值的时候,都在调用
_PropertyInfo.GetValue(x, null);
可想而知,如果要筛选的记录非常多的话,那么性能无疑会受到影响。
为了提升性能,可以使用表达式树将反射调用改为委托调用,
具体代码如下:

public class FastPropertyComparer<T> : IEqualityComparer<T>
{
    private Func<T, Object> getPropertyValueFunc = null;
    /// <summary>
    /// 通过propertyName 获取PropertyInfo对象
    /// </summary>
    /// <param name="propertyName"></param>
    public FastPropertyComparer(string propertyName)
    {
        PropertyInfo _PropertyInfo = typeof(T).GetProperty(propertyName,
        BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public);
        if (_PropertyInfo == null)
        {
            throw new ArgumentException(string.Format("{0} is not a property of type {1}.",
                propertyName, typeof(T)));
        }
        ParameterExpression expPara = Expression.Parameter(typeof(T), "obj");
        MemberExpression me = Expression.Property(expPara, _PropertyInfo);
        getPropertyValueFunc = Expression.Lambda<Func<T, object>>(me, expPara).Compile();
    }
    #region IEqualityComparer<T> Members
    public bool Equals(T x, T y)
    {
        object xValue = getPropertyValueFunc(x);
        object yValue = getPropertyValueFunc(y);
        if (xValue == null)
            return yValue == null;
        return xValue.Equals(yValue);
    }
    public int GetHashCode(T obj)
    {
        object propertyValue = getPropertyValueFunc(obj);
        if (propertyValue == null)
            return 0;
        else
            return propertyValue.GetHashCode();
    }
    #endregion
}

可以看到现在获取值只需要getPropertyValueFunc(obj) 就可以了。
使用的时候:
var distinctProduct = products.Distinct(new FastPropertyComparer<Product>("Id")).ToList();

相关文章

  • C#实现过滤sql特殊字符的方法集合

    C#实现过滤sql特殊字符的方法集合

    这篇文章主要介绍了C#实现过滤sql特殊字符的方法,以实例形式分析总结了C#针对SQL危险字符的几种常用的过滤技巧,非常具有实用价值,需要的朋友可以参考下
    2015-11-11
  • C#构建树形结构数据(全部构建,查找构建)

    C#构建树形结构数据(全部构建,查找构建)

    这篇文章主要介绍了C#构建树形结构数据(全部构建,查找构建),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-10-10
  • C#中dotnetcharting的用法实例详解

    C#中dotnetcharting的用法实例详解

    这篇文章主要介绍了C#中dotnetcharting的用法,以实例形式详细分析了基于dotnetcharting的图表绘制的各种常用方法,是非常实用的技巧,需要的朋友可以参考下
    2014-10-10
  • C#调用VB进行简繁转换的方法

    C#调用VB进行简繁转换的方法

    这篇文章主要介绍了C#调用VB进行简繁转换的方法,通过调用VB的动态链接库实现繁简转换的技巧,非常具有实用价值,需要的朋友可以参考下
    2015-02-02
  • C# LINQ查询表达式及对应LAMBDA表达式的用法

    C# LINQ查询表达式及对应LAMBDA表达式的用法

    这篇文章主要介绍了C# LINQ查询表达式及对应LAMBDA表达式的用法,帮助大家更好的理解和学习使用c#,感兴趣的朋友可以了解下
    2021-04-04
  • 详解C#中线程传参,返回值和多线程冲突问题的解决

    详解C#中线程传参,返回值和多线程冲突问题的解决

    这篇文章主要为大家详细介绍了C#中线程传参,返回值和多线程冲突问题的解决方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
    2022-11-11
  • C#中使用gRPC通讯的示例详解

    C#中使用gRPC通讯的示例详解

    这篇文章主要为大家详细介绍了C#中如何使用gRPC通讯,包括GRPC文件的创建生成、服务端和客户端函数类库的封装等,需要的可以了解下
    2024-04-04
  • Unity中协程IEnumerator的使用方法介绍详解

    Unity中协程IEnumerator的使用方法介绍详解

    本文主要介绍了Unity中协程IEnumerator的使用方法介绍详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-06-06
  • C#处理文本文件TXT实例详解

    C#处理文本文件TXT实例详解

    这篇文章主要介绍了C#处理文本文件TXT的方法,以实例形式详细分析了txt文本文件的读取、修改及打印等功能的实现技巧,需要的朋友可以参考下
    2015-02-02
  • 基于数据类型转换(装箱与拆箱)与常量详解

    基于数据类型转换(装箱与拆箱)与常量详解

    下面小编就为大家分享一篇基于数据类型转换(装箱与拆箱)与常量详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2017-11-11

最新评论