且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用LINQ在集合中查找和删除重复对象?

更新时间:2023-02-17 18:02:20

您可以使用 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() ) );