Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find duplicate items in list<>? [duplicate]

Tags:

c#

list

linq

I have:

List<string> list = new List<string>() { "a", "a", "b", "b", "r", "t" };

How can I get only "a","b"?

I tried to do like this:

List<string> list = new List<string>() { "a", "a", "b", "b", "r", "t" };
List<string> test_list = new List<string>(); 

test_list = list.Distinct().ToList();

Now test_list has {"a", "b", "r", "t"}
And then:

test_list = test_list.Except(list).ToList();

So that was my fail point, cause Except() deleted all elements.

Could you help me with solution?

like image 948
Monopompom Avatar asked Apr 07 '13 19:04

Monopompom


People also ask

Can a list have duplicate values in Python?

Python list can contain duplicate elements.


1 Answers

List<string> list = new List<string>() { "a", "a", "b", "b", "r", "t" };

var dups = list.GroupBy(x => x)
    .Where(x => x.Count() > 1)
    .Select(x => x.Key)
    .ToList();
like image 132
I4V Avatar answered Sep 25 '22 10:09

I4V