C# Distinct方法的使用笔记
引自:http://blog.csdn.net/shaopengfei/article/details/36426763
从C# 3.0开始提供了Distinct方法,这对于集合的使用有了更为丰富的方法,经过在网上搜索相应的资源,发现有关这方面的写的好的文章还是不少的。而且为了扩展Linq的使用不方便的地方,有一些办法非常有效。由于本人工作中的需要,有一些功能暂时没有用到那么深入,现在只把最简单的一些功能分享出来,整理出来。
简单一维集合的使用:
- List<int> ages = new List<int> { 21, 46, 46, 55, 17, 21, 55, 55 };
- List<string> names = new List<string> { "wang", "li", "zhang", "li", "wang", "chen", "he", "wang" };
- IEnumerable<int> distinctAges = ages.Distinct();
- Console.WriteLine("Distinct ages:");
- foreach (int age in distinctAges)
- {
- Console.WriteLine(age);
- }
- var distinctNames = names.Distinct();
- Console.WriteLine("\nDistinct names:");
- foreach (string name in distinctNames)
- {
- Console.WriteLine(name);
- }
- 在这段代码中,是最简单的Distinct()方法的使用。使用了集合接口IEnumerable,以及隐式类型var,至于这两种用法有什么区别,没有研究出来。
- 但是如果象下面这样的代码,是错误的!
- List<int> disAge = ages.Distinct();
- 正确的方法应该是:
- List<int> ages = new List<int> { 21, 46, 46, 55, 17, 21, 55, 55 };
- List<int> disAge = ages.Distinct().ToList();
- foreach (int a in disAge)
- Console.WriteLine(a);
- 也就是说Distinct()方法的返回集合类型是一个接口,不是具体的集合,所以需要用一个ToList()。
自定义类的使用:
- 首先我们看MSDN上给出的例子,先定义一个产品类:
- public class Product : IEquatable<Product>
- {
- public string Name { get; set; }
- public int Code { get; set; }
- public bool Equals(Product other)
- {
- //Check whether the compared object is null.
- if (Object.ReferenceEquals(other, null)) return false;
- //Check whether the compared object references the same data.
- if (Object.ReferenceEquals(this, other)) return true;
- //Check whether the products' properties are equal.
- return Code.Equals(other.Code) && Name.Equals(other.Name);
- }
- // If Equals() returns true for a pair of objects
- // then GetHashCode() must return the same value for these objects.
- public override int GetHashCode()
- {
- //Get hash code for the Name field if it is not null.
- int hashProductName = Name == null ? 0 : Name.GetHashCode();
- //Get hash code for the Code field.
- int hashProductCode = Code.GetHashCode();
- //Calculate the hash code for the product.
- return hashProductName ^ hashProductCode;
- }
- }
- 在主函数里,是这样用的:
- static void Main(string[] args)
- {
- Product[] products =
- {
- new Product { Name = "apple", Code = 9 },
- new Product { Name = "orange", Code = 4 },
- new Product { Name = "apple", Code = 9 },
- new Product { Name = "lemon", Code = 12 }
- };
- //Exclude duplicates.
- IEnumerable<Product> noduplicates =
- products.Distinct();
- foreach (var product in noduplicates)
- Console.WriteLine(product.Name + " " + product.Code);
- }
- 这样的输出是:
- /*
- This code produces the following output:
- apple 9
- orange 4
- lemon 12
- */
- 但是现在的问题是,如果我们把主函数里改成这样:
- static void Main(string[] args)
- {
- Product[] products =
- {
- new Product { Name = "Smallapple", Code = 9 },
- new Product { Name = "orange", Code = 4 },
- new Product { Name = "Bigapple", Code = 9 },
- new Product { Name = "lemon", Code = 12 }
- };
- //Exclude duplicates.
- IEnumerable<Product> noduplicates =
- products.Distinct();
- foreach (var product in noduplicates)
- Console.WriteLine(product.Name + " " + product.Code);
- }
- 这样的输出是:
- /*
- This code produces the following output:
- Smallapple 9
- orange 4
- Bigapple 9
- lemon 12
- */
- 我们的问题是,如果想按Code来索引,想找出Code唯一的这些成员,那么这里就需要重新定义一个对Code比较的类,或者再扩展成泛型类,但是这样非常繁琐。
博客鹤冲天的改进办法(以下均转自这个博客)
- 首先,创建一个通用比较的类,实现IEqualityComparer<T>接口:
- 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));
- }
- }
- 借助上面这个类,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));
- }
- }
- 下面的使用就很简单了:
- Product[] products =
- {
- new Product { Name = "Smallapple", Code = 9 },
- new Product { Name = "orange", Code = 4 },
- new Product { Name = "Bigapple", Code = 9 },
- new Product { Name = "lemon", Code = 12 }
- };
- var p1 = products.Distinct(p => p.Code);
- foreach (Product pro in p1)
- Console.WriteLine(pro.Name + "," + pro.Code);
- var p2 = products.Distinct(p => p.Name);
- foreach (Product pro in p2)
- Console.WriteLine(pro.Name + "," + pro.Code);
- 可以看到,加上Linq表达式,可以方便的对自定义类的任意字段进行Distinct的处理。
C# Distinct方法的使用笔记的更多相关文章
- 重写类的Equals以及重写Linq下的Distinct方法
当自定义一个类的时候,如果需要用到对比的功能,可以自己重写Equals方法,最整洁的方法是重写GetHashCode()方法. 但是,这个方法只适用于对象自身的对比(如if(a==b))以及字典下的C ...
- 如何很好的使用Linq的Distinct方法
Person1: Id=1, Name="Test1" Person2: Id=1, Name="Test1" Person3: Id=2, Name=&quo ...
- Linq的Distinct方法的扩展
原文地址:如何很好的使用Linq的Distinct方法 Person1: Id=1, Name="Test1" Person2: Id=1, Name="Test1&qu ...
- 【C#】详解使用Enumerable.Distinct方法去重
Enumerable.Distinct 方法 是常用的LINQ扩展方法,属于System.Linq的Enumerable方法,可用于去除数组.集合中的重复元素,还可以自定义去重的规则. 有两个重载方法 ...
- 如何使用Linq或EF来对数据去重——Distinct方法详解
刚开始接触LINQ时使用distinct去重时和大家一样遇到了一些麻烦,很感谢 http://www.cnblogs.com/A_ming/archive/2013/05/24/3097062.htm ...
- 扩展Linq的Distinct方法动态根据条件进行筛选
声明为了方便自己查看所以引用 原文地址:http://www.cnblogs.com/A_ming/archive/2013/05/24/3097062.html Person1: Id=1, Nam ...
- Linq Enumerable.Distinct方法去重
Enumerable.Distinct 方法 是常用的LINQ扩展方法,属于System.Linq的Enumerable方法,可用于去除数组.集合中的重复元素,还可以自定义去重的规则. 有两个重载方法 ...
- 【转载】C#中通过Distinct方法对List集合进行去重
在C#的List集合对象中,可以使用Distinct方法来对List集合元素进行去重,如果list集合内部元素为值类型,则Distinct方法根据值类型是否相等来判断去重,如果List集合内部元素为引 ...
- DISTINCT 方法用于返回唯一不同的值 。
DISTINCT 方法用于返回唯一不同的值 . 例如: $Model->distinct(true)->field('name')->select(); 生成的SQL语句是: SEL ...
随机推荐
- codeforces 651A Joysticks
A. Joysticks time limit per test 1 second memory limit per test 256 megabytes input standard input o ...
- CSS构造表格
表格的基础构造 边距和边线应用 隐藏和删除应用 简单表格 table { width:auto; border-collapse:collapse;(把单元格空隙合并起来) m ...
- CodeForces 732D Exams (二分)
题意:某人要考试,有n天考m个科目,然后有m个科目要考试的时间和要复习多少天才能做,问你他最早考完所有科目是什么时间. 析:二分答案,然后在判断时,直接就是倒着判,很明显后出来的优先,也就是一个栈. ...
- iOS开发-为程序添加应用设置
一.设置捆绑包 设置捆绑包是应用自带的一组文件,用于告诉设置该应用期望得到用户的哪些偏好设置. 新建设置捆绑包:Command+N,在iOS部分中的Resource,选择Settings Bundle ...
- 【SQL】导出表数据到Excel中
打开数据库之后点击新建表查询: ------------------------------------------------------------------------------------ ...
- Nginx学习之十一-Nginx启动框架处理流程
Nginx启动过程流程图 下面首先给出Nginx启动过程的流程图: ngx_cycle_t结构体 Nginx的启动初始化在src/core/nginx.c的main函数中完成,当然main函数是整个N ...
- 【不积跬步,无以致千里】vim复制
用vim这么久 了,始终也不知道怎么在vim中使用系统粘贴板,通常要在网上复制一段代码都是先gedit打开文件,中键粘贴后关闭,然后再用vim打开编辑,真的不 爽:上次论坛上有人问到了怎么在vim中使 ...
- 如何知道PostgreSQL数据库下每个数据库所对应的目录
base目录,这是所有数据库目录的父目录. 在base目录下第一层,每个目录就是一个数据库所对应的文件. 那么如何知道哪个目录对应哪个数据呢? 查询如下:先看数据库列表 [pgsql@localhos ...
- Codeforces Gym 100002 D"Decoding Task" 数学
Problem D"Decoding Task" Time Limit: 1 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com ...
- gulp如何自定义插件
gulp是基于”流“的构建工具,上层流的输出就是下层流的输入,为了更好的支持链式操作,可以使用through2或者map-stream这两个库来对node stream做一层包装 这里,我们就使用th ...