刚看了篇文章 《Linq的Distinct太不给力了》,文中给出了一个解决办法,略显复杂。

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

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

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

可通过扩展方法实现:

Distinct 扩展方法

首先,创建一个通用比较的类,实现 IEqualityComparer<T> 接口:

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

第 17 行,用到了 EqualityComparer<T> 类,本文最后有简要说明

借助上面这个类,Distinct 扩展方法就很好写了:

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

呵呵,简单吧!

Distinct 使用示例

根据 ID :

 var data1 = new Person[] {
new Person{ ID = , Name = "鹤冲天"},
new Person{ ID = , Name = "ldp"}
};
var ps1 = data1
.Distinct(p => p.ID)
.ToArray();

根据 Name:

 var data2 = new Person[] {
new Person{ ID = , Name = "鹤冲天"},
new Person{ ID = , Name = "鹤冲天"}
};
var ps2 = data2
.Distinct(p => p.Name)
.ToArray();

看了回复后,我做了些改进,推荐使用下面的方式

改进

回复中有朋友提到“不区分大小写地排除重复的字符串”,也不难实现,只需要把上面的代码改进下就 OK:

CommonEqualityComparer<T, V> 类:

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

Distinct 扩展方法

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

借助可选参数,这两个扩展方法也可以合成一个:

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

(同样,CommonEqualityComparer<T, V>类的两个构造函数也可以合二为一)

使用示例:

 var data3 = new Person[] {
new Person{ ID = , Name = "LDP"},
new Person{ ID = , Name = "ldp"}
};
var ps3 = data3
.Distinct(p => p.Name, StringComparer.CurrentCultureIgnoreCase)
.ToArray();

EqualityComparer<T> 类 简要说明

EqualityComparer<T>为 IEqualityComparer<T> 泛型接口的实现提供基类,它在 .net 4 中有五个重要的子类,见下图:

这五个子类分别用不同类型数据的相等性比较,从类名我们可以略知一二。

这五个子类都是内部类(internal),不能直接访问,EqualityComparer<T> 类提供一个简单的属性 Default。EqualityComparer<T> 会根据传入的 T 的类型,加载不同的子类,并会予以缓存提高性能。

c#扩展方法奇思妙用》系统文章从 2009 年 08 月开始写起,到现在一共有了 22 篇,欢迎阅读:

基础篇: 中文处理string 常用扩展byte 常用扩展Random 扩展Dictionary<TKey, TValue> 扩展WhereIf 扩展IsBetween 通用扩展WhereIf 扩展Distinct 扩展
高级篇: 改进 Scottgu 的 "In" 扩展Aggregate扩展其改进Enumerable.Cast<T>应用对扩展进行分组管理ToString(string format) 扩展WinForm 控件选择器树”通用遍历器Type类扩展
变态篇: 由Fibonacci数列引出“委托扩展”及“递推递归委托”封装 if/else、swith/case及whileswitch/case 组扩展string 的翻身革命
性能篇 扩展方法性能初测
MVC篇: 巧用扩展方法优先级,美化所有页面TextBoxFor文本框

-------------------

思想火花,照亮世界

文章来源:http://www.cnblogs.com/ldp615/archive/2011/08/01/distinct-entension.html

c# 扩展方法奇思妙用基础篇八:Distinct 扩展的更多相关文章

  1. c# 扩展方法奇思妙用基础篇八:Distinct 扩展(转载)

    转载地址:http://www.cnblogs.com/ldp615/archive/2011/08/01/distinct-entension.html 刚看了篇文章 <Linq的Distin ...

  2. c# 扩展方法奇思妙用基础篇五:Dictionary<TKey, TValue> 扩展

    Dictionary<TKey, TValue>类是常用的一个基础类,但用起来有时确不是很方便.本文逐一讨论,并使用扩展方法解决. 向字典中添加键和值 添加键和值使用 Add 方法,但很多 ...

  3. c# 扩展方法奇思妙用基础篇九:Expression 扩展

    http://www.cnblogs.com/ldp615/archive/2011/09/15/expression-extension-methods.html .net 中创建 Expressi ...

  4. C# 扩展方法奇思妙用高级篇六:WinForm 控件选择器

    在Web开发中,jQuery提供了功能异常强大的$选择器来帮助我们获取页面上的对象.但在WinForm中,.Net似乎没有这样一个使用起来比较方便的选择器.好在我们有扩展方法,可以很方便的打造一个. ...

  5. c# 扩展方法 奇思妙用 高级篇 九:OrderBy(string propertyName, bool desc)

    下面是 Queryable 类 中最常用的两个排序的扩展方法: 1 2 public static IOrderedQueryable<TSource> OrderBy<TSourc ...

  6. c# 扩展方法奇思妙用

    # 扩展方法出来已久,介绍扩展方法的文章也很多,但都是笼统的.本人最近一直在思考扩展方法的应用,也悟出了一些,准备将这最近一段时间对扩展方法的思考,写成一个系列文章.每个文章只介绍一个应用方面,篇幅不 ...

  7. c# 扩展方法奇思妙用集锦

    本文转载:http://www.cnblogs.com/ldp615/archive/2009/08/07/1541404.html 其中本人觉得很经典的:c# 扩展方法奇思妙用基础篇五:Dictio ...

  8. 【mongoDB基础篇②】PHP-mongo扩展的编译以及使用

    安装PHP-mongo扩展 安装php-mongo扩展和安装其他php扩展的步骤一样: #1.首先上http://pecl.php.net上面搜索mongo,得到下载地址 wget http://pe ...

  9. Python基础篇(八)

    key words:私有变量,类静态变量,生成器,导入Python模块,r查看模块可以使用的函数,查看帮助信息,启动外部程序,集合,堆,时间模块,random模块,shelve模块,文件读取等 > ...

随机推荐

  1. WebLogic Server 12.1.2后的字符型安装模式

    weblogic Server 12.1.1全部都可以用原来方式. WebLogic Server 12.1.2后已经取消了console安装模式,目前只有gui和静默安装模式.并且安装方式下也有很大 ...

  2. supervisord的环境变量的设置

    在python中引用jar包,使用java的功能,需要使用三方包:pyjnius from jnius import autoclass 需要java环境,因此需要设置JAVA_HOME环境变量. 但 ...

  3. Linux内核regulator架构和编写

    电源种类介绍 (百度百科)LDO是low dropout regulator,意为低压差线性稳压器,是相对于传统的线性稳压器来说的.传统的线性稳压器,如78xx系列的芯片都要求输入电压要比输出电压高出 ...

  4. 鸟哥的linux私房菜服务器架设篇学习记录之进修专区与架设服务器的准备工作

  5. http://blog.csdn.net/jhg1204/article/details/45013987

    http://blog.csdn.net/jhg1204/article/details/45013987

  6. Spark Streaming on Kafka解析和安装实战

    本课分2部分讲解: 第一部分,讲解Kafka的概念.架构和用例场景: 第二部分,讲解Kafka的安装和实战. 由于时间关系,今天的课程只讲到如何用官网的例子验证Kafka的安装是否成功.后续课程会接着 ...

  7. require.js - 详解

    测试结构如下 index.html <!DOCTYPE html> <html lang="en"> <head> <meta chars ...

  8. 【 D3.js 入门系列 --- 5 】 怎样加入坐标轴

    本人的个人博客为: www.ourd3js.com csdn博客为: blog.csdn.net/lzhlzz 转载请注明出处.谢谢.      第3节中做了一个图标.但没有为它加入一个对应的坐标轴. ...

  9. 我对GFWed的一些自己的见解

    首先来听听维基百科对GFWed的说明 防火长城(英语:Great Firewall of China.经常使用简称:GFW,中文也称中国国家防火墙或防火长城[1],中国大陆民众俗称防火墙[2].功夫网 ...

  10. 由friend用法引出的声明与定义那些事儿

    今天遇到了一个问题,大致描述一下就是有两个类A和B.我想达到如下效果:B是A的友元,同时A是B的类类型成员. 第一次尝试,在B.h中包含A.h,在A.h中包含B.h,在A类中声明friend clas ...