Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 967
paul richardson Avatar asked May 16 '13 20:05

paul richardson


2 Answers

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.

like image 175
Sergey Kalinichenko Avatar answered Oct 03 '22 14:10

Sergey Kalinichenko


var itemsExistingExactlyOnce = list.GroupBy(x => x)
    .Where(group => group.Count() == 1)
    .Select(group => group.Key);
like image 31
Servy Avatar answered Oct 03 '22 14:10

Servy