Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove non-duplicates from a list in C#

Tags:

c#

linq

I want to do the opposite thing as here

I have a list and I know how to remove the duplicates. But I want to have an option where the user can select which duplicate to keep. Some query quere I can have a list that will only show the duplicates. Something like:

Lets say my list is:

"tom" "bob" "Frank" "bob" "Lacey" "Frank"

I know that if I use the distinct method I will get:

"tom" "bob" "Frank" "Lacey"

I don't know what method to I have to use to get:

"bob" "bob" "frank" "frank"

or to get

"bob" "frank"

cause those are the ones that repeat.

like image 283
Tono Nam Avatar asked May 25 '11 17:05

Tono Nam


People also ask

Which list does not contain duplicates?

Duplicates : ArrayList allows duplicate values while HashSet doesn't allow duplicates values.

Can conditional formatting remove duplicates?

To remove duplicate values, click Data > Data Tools > Remove Duplicates. To highlight unique or duplicate values, use the Conditional Formatting command in the Style group on the Home tab.


1 Answers

You can use GroupBy to filter out the items that only occur once, then flatten the remaining items back into a list:

var resultList = list.GroupBy(x => x)
                     .Where(g => g.Count() > 1)
                     .SelectMany(g => g)
                     .ToList();
like image 104
BrokenGlass Avatar answered Oct 06 '22 03:10

BrokenGlass