且构网

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

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

更新时间:2023-02-17 19:07:33

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

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() ) );