C# LINQ find duplicates in List

The easiest way to solve the problem is to group the elements based on their value, and then pick a representative of the group if there are more than one element in the group. In linq, this translates to:

var query = lst.GroupBy(x=>x)

If you want to know how many times the elements are repeated, you can use:

var query = lst.GroupBy(x=>x)
              .Select(y=> new { Element = y.Key, Counter = y.Count()})

This will return a List of an anonymous type, and each element will have the properties Element and Counter, to retrieve the informations you need.

And lastly, if it’s a dictionary you are looking for, you can use

var query = lst.GroupBy(x=>x)

This will return a dictionary, with your element as key, and the number of times it’s repeated as value.


source: http://stackoverflow.com/questions/18547354/c-sharp-linq-find-duplicates-in-list


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s