从C#列表中删除重复项和原始项 [英] 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.
我可以覆盖Equals和GetHashCode,然后使用Distinct,但这只会删除重复项.我需要同时删除原始文件和重复文件...任何有关优雅的想法,因此我不必使用锤子.
I can overide Equals and GetHashCode and then use Distinct but this only removes the duplicate. I need to remove both original and duplicate... Any ideas for something elegant so I don't have to use a hammer.
推荐答案
您可以使用 GroupBy
,然后使用 Where(g => g.Count()== 1)
过滤掉所有重复的记录:
You can use GroupBy
, followed by Where (g => g.Count() == 1)
to filter out all records that have duplicates:
var res = orig.GroupBy(x => x).Where(g => g.Count() == 1).Select(g => g.Key);
为此,您仍然需要覆盖 GetHashCode
和 Equals
.
In order for this to work, you still need to override GetHashCode
and Equals
.
这篇关于从C#列表中删除重复项和原始项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!