如何使用LINQ查找和删除集合中的重复对象? [英] How to find and remove duplicate objects in a collection using LINQ?
问题描述
CollectionBase
,它是一个容器类,用于保存我的第一个类中的多个对象。 <我的问题是,我想删除重复的对象(例如具有相同日期,相同小数,相同整数和相同字符串的对象)。有可以写LINQ查询查找和删除重复项吗?或者至少找到他们?
您可以使用 有两个重载 - 一个使用默认的类型比较器(对于自定义类型将调用类型上的 如果您想要找到重复的内容,您可以使用 要从像 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 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 There are two overloads - one uses the default equality comparer for your type (which for a custom type will call the If you want to just find the duplicates, you can use To remove duplicates from something like an
这篇关于如何使用LINQ查找和删除集合中的重复对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
Equals()
方法)。第二个允许您提供自己的平等比较器。他们都返回代表您的原始集合的新序列,而不重复。 b
$ b GroupBy
来执行此操作:
var groupsWithDups = list。 GroupBy(x => new {A = xA,B = xB,...},x => x)
.Where(g => g.Count()> 1);
IList<>
你可以做:
yourList.RemoveAll(yourList.Except(yourList.Distinct()));
CollectionBase
, which is a container class for holding multiple objects from my first class.Distinct
operator.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
to do so:var groupsWithDups = list.GroupBy( x => new { A = x.A, B = x.B, ... }, x => x )
.Where( g => g.Count() > 1 );
IList<>
you could do:yourList.RemoveAll( yourList.Except( yourList.Distinct() ) );