C# 中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 的结果是:

因为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());

结果如下:

现在假设我们要 按照 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"));

结果如下:

为什么微软不提供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();

http://www.cnblogs.com/joyang/p/5702472.html
时间: 2024-08-09 06:35:02

C# 中distinct的使用的相关文章

mysql 去除重复 Select中DISTINCT关键字的用法

在使用mysql时,有时需要查询出某个字段不重复的记录,虽然mysql提供 有distinct这个关键字来过滤掉多余的重复记录只保留一条,但往往只用它来返回不重复记录的条数,而不是用它来返回不重记录的所有值.其原因是 distinct只能返回它的目标字段,而无法返回其它字段,这个问题让我困扰了很久,用distinct不能解决的话,我只有用二重循环查询来解决,而 这样对于一个数据量非常大的站来说,无疑是会直接影响到效率的.所以我花了很多时间来研究这个问题,网上也查不到解决方案,期间把容容拉来帮忙,

SQL中distinct的用法和left join查询的含义

SQL中distinct的用法 1.作用于单列 2.作用于多列 3.COUNT统计 4.distinct必须放在开头 5.其他 在表中,可能会包含重复值.这并不成问题,不过,有时您也许希望仅仅列出不同(distinct)的值.关键词 distinct用于返回唯一不同的值. 表A: 表B: 1.作用于单列 select distinct name from A 执行后结果如下: 2.作用于多列 示例2.1 select distinct name, id from A 执行后结果如下: 实际上是根

SQL中distinct的用法

1.作用于单列 2.作用于多列 3.COUNT统计 4.distinct必须放在开头 5.其他 在表中,可能会包含重复值.这并不成问题,不过,有时您也许希望仅仅列出不同(distinct)的值.关键词 distinct用于返回唯一不同的值. 表A: 表B: 1.作用于单列 select distinct name from A 执行后结果如下: 2.作用于多列 示例2.1 select distinct name, id from A 执行后结果如下: 实际上是根据name和id两个字段来去重的

sql中Distinct的使用

作用:消除重复的数值 一.如: 1 select id from T1 2 3 select distinct id from T1 二者的检索效果如下: distinct可以用来修饰多列,如: 1 select distinct id,name from T1 效果: 发现检索的结果自动按照id列进行排序,再比如: 1 select distinct name,id from T1 发现的结果自动按照name列进行排序.也就是说在执行select语句时,总会对要被检索的列,进行默认的排序,如上

SQL中distinct的用法(转自博主:Rain Man)

在表中,可能会包含重复值.这并不成问题,不过,有时您也许希望仅仅列出不同(distinct)的值.关键词 distinct用于返回唯一不同的值. 表A: 示例1 select distinct name from A 执行后结果如下: 示例2 select distinct name, id from A 执行后结果如下: 实际上是根据“name+id”来去重,distinct同时作用在了name和id上,这种方式Access和SQL Server同时支持. 示例3:统计 select coun

MySQL中distinct的使用方法

一.基本使用 distinct一般是用来去除查询结果中的重复记录的,而且这个语句在select.insert.delete和update中只可以在select中使用,具体的语法如下: select distinct expression[,expression...] from tables [where conditions]; 1 这里的expressions可以是多个字段.本文的所有操作都是针对如下示例表的: CREATE TABLE `NewTable` ( `id` int(11) N

mongoDB中distinct的使用

需求:在mongodb中查询一个类型(数据库中可能百万条数据)用作下拉列表查询.在工具中用 db.getCollection('order').distinct("typeName") 即可实现.java 代码:MongoCollection<Document> coll = this.client.getDatabase(this.databaseName).getCollection('order');//获得mongodb数据库连接 getCollection表名//

ElasticSearch中&quot;distinct&quot;,&quot;count&quot;和&quot;group by&quot;的实现

最近在业务中需要使用ES来进行数据查询,在某些场景下需要对数据进行去重,以及去重后的统计.为了方便大家理解,特意从SQL角度,方便大家能够理解ES查询语句. 1 - distinct SELECT DISTINCT(user_id) FROM table WHERE user_id_type = 3; { "query": { "term": { "user_id_type": 3 } }, "collapse": { &qu

深入理解Oracle中distinct关键字

distinct这个关键字来过滤掉多余的重复记录只保留一条,但往往只用它来返回不重复记录的条数,而不是用它来返回不重记录的所有值.其原因是distinct只有用二重循环查询来解决,而这样对于一个数据量非常大的站来说,无疑是会直接影响到效率的. distinct 会对返回的结果集进行排序,所以,最好和order by 结合使用,可以提高效率. 一.distinct 基本用法 1.用于单列  1 select distinct name from A  执行后结果如下: 2.作用于多列  1 sel