[英]Remove Duplicates and Original from C# List
I have a List of custom types where I want to remove the duplicate and the original if a duplicate is found. 我有一个自定义类型列表,我想删除副本和原始如果找到重复。 Can only be one possible duplicate. 只能是一个可能的副本。
I can overide Equals and GetHashCode and then use Distinct but this only removes the duplicate. 我可以覆盖Equals和GetHashCode然后使用Distinct但这只删除了重复。 I need to remove both original and duplicate... Any ideas for something elegant so I don't have to use a hammer. 我需要删除原始和重复......任何优雅的想法,所以我不必使用锤子。
You can use GroupBy
, followed by Where (g => g.Count() == 1)
to filter out all records that have duplicates: 您可以使用GroupBy
,然后使用Where (g => g.Count() == 1)
过滤掉所有具有重复项的记录:
var res = orig.GroupBy(x => x).Where(g => g.Count() == 1).Select(g => g.Key);
In order for this to work, you still need to override GetHashCode
and Equals
. 为了使其工作,您仍然需要覆盖GetHashCode
和Equals
。
var itemsExistingExactlyOnce = list.GroupBy(x => x)
.Where(group => group.Count() == 1)
.Select(group => group.Key);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.