How to find all duplicate from a List<string>?

Steven Spielberg picture Steven Spielberg · Jan 2, 2011 · Viewed 153.5k times · Source

I have a List<string> which has some words duplicated. I need to find all words which are duplicates.

Any trick to get them all?

Answer

Giuseppe Ottaviano picture Giuseppe Ottaviano · Jan 2, 2011

In .NET framework 3.5 and above you can use Enumerable.GroupBy which returns an enumerable of enumerables of duplicate keys, and then filter out any of the enumerables that have a Count of <=1, then select their keys to get back down to a single enumerable:

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