Alex Rivera | Logout

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

Asked 2011-01-02T12:02:54.080
128

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?

Edit
Report

1 Answer

230

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);
answered 2011-01-02T12:10:58.553

Your Answer