如何使用LINQ在集合中查找和删除重复对象? [英] How to find and remove duplicate objects in a collection using LINQ?
问题描述
我有一个简单的类表示一个对象。它有5个属性(日期,2小数,整数和字符串)。我有一个集合类,派生自 CollectionBase
,它是一个容器类,用于保存我的第一个类的多个对象。
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?
推荐答案
您可以使用 Distinct
运算符。
You can remove duplicates using the Distinct
operator.
有两个重载 - 一个使用默认的相等比较器类型(对于一个自定义类型将调用 Equals()
方法类型) 。第二个允许你提供自己的平等比较器。它们都会返回代表原始集的新序列,而不会出现重复。 这两个重载实际上都不会修改您的初始集合 - 它们都会返回排除重复的新序列。。
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<>
你可以做:
yourList.RemoveAll( yourList.Except( yourList.Distinct() ) );
这篇关于如何使用LINQ在集合中查找和删除重复对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!