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. 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:
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
.
var itemsExistingExactlyOnce = list.GroupBy(x => x)
.Where(group => group.Count() == 1)
.Select(group => group.Key);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With