paul richardson
paul richardson

Reputation: 53

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. I need to remove both original and duplicate... Any ideas for something elegant so I don't have to use a hammer.

Upvotes: 5

Views: 450

Answers (2)

Servy
Servy

Reputation: 203817

var itemsExistingExactlyOnce = list.GroupBy(x => x)
    .Where(group => group.Count() == 1)
    .Select(group => group.Key);

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726539

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.

Upvotes: 6

Related Questions