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

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

问题描述

我有一个简单的类代表一个对象。它有5个属性(一个日期,2个小数,一个整数和一个字符串)。我有一个集合类,派生自 CollectionBase ,它是一个容器类,用于保存我的第一个类中的多个对象。



<我的问题是,我想删除重复的对象(例如具有相同日期,相同小数,相同整数和相同字符串的对象)。有可以写LINQ查询查找和删除重复项吗?或者至少找到他们?

解决方案

您可以使用

有两个重载 - 一个使用默认的类型比较器(对于自定义类型将调用类型上的 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())); 


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.

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.

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..

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

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

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

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

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