如何查找和使用LINQ集合中删除重复的对象? [英] How to find and remove duplicate objects in a collection using LINQ?

查看:151
本文介绍了如何查找和使用LINQ集合中删除重复的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的类重presenting的对象。它有5个属性(日期,2位小数,整数,字符串)。我有一个集合类,来源于 Col​​lectionBase的,这是一个容器类持有多个对象,从我的第一课。

I have a simple class representing an object. It has 5 properties (a date, 2 decimals, an integer and a string). I have a collection class, derived from CollectionBase, which is a container class for holding multiple objects from my first class.

我的问题是,我想删除重复的对象(如对象具有相同日期,相同的小数,同样的整数和相同的字符串)。有一个LINQ查询,我可以写找到并删除重复?或者找到他们最起码?

My question is, I want to remove duplicate objects (e.g. objects that have the same date, same decimals, same integers and same string). Is there a LINQ query I can write to find and remove duplicates? Or find them at the very least?

推荐答案

您可以通过删除重复的 分明 运营商。

You can remove duplicates using the Distinct operator.

有两个重载 - 一个使用默认的相等比较器为你的类型(这对于一个自定义类型会调用等于()方法的类型)。第二个,您可以提供自己的相等比较。他们都返回的新序列的再presenting你原来的设定没有重复。 既不超载实际修改您最初的集合 - 它们都返回一个新的序列,排除重复

There are two overloads - one uses the default equality comparer for your type (which for a custom type will call the Equals() method on the type). The second allows you to supply your own equality comparer. They both return a new sequence representing your original set without duplicates. Neither overload actually modifies your initial collection - they both return a new sequence that excludes duplicates..

如果您只想找到重复的,你可以使用 GROUPBY 这样做的:

If you want to just find the duplicates, you can use GroupBy to do so:

var groupsWithDups = list.GroupBy( x => new { A = x.A, B = x.B, ... }, x => x ) 
                         .Where( g => g.Count() > 1 );

要由类似的删除重复的IList<> ,你可以这样做:

To remove duplicates from something like an IList<> you could do:

yourList.RemoveAll( yourList.Except( yourList.Distinct() ) );

这篇关于如何查找和使用LINQ集合中删除重复的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆