Find duplicate with Linq

This small tips discussed about how to get list of duplicate items for the collection that we do in sql.
For example I have to get list of the email id which is get entered in user table more than one time.

	
SELECT email,
  COUNT(email) AS NumOccurrences
FROM users
GROUP BY email
HAVING ( COUNT(email) > 1 )

Linq query work same as on the set of collection and which make use of count

DataClassesDataContext db = new DataClassesDataContext();
var duplicates = db.Users
    .GroupBy(i => i.emailid)
    .Where(g => g.Count() > 1)
    .Select(g => g.emailid);
foreach (var d in duplicates)
    Console.WriteLine(d);

So by using above query you can easily achieve task of finding duplicate for your set of collection.

Pranay Rana

Pranay is MVB on DZone and working as a Senior Software engineer. Doing Web development using Asp.Net ,C#, MS sql server, JQuery/Javascript that he had experience of 4.3 years now. For himdef. of programming is : Programming is something that you do once and that get used by multiple for many years You can visit him on his blog - http://pranayamr.blogspot.com/ Follow on twitter : @pranayamr

2 Comments to “Find duplicate with Linq”

  1. It is really a great and useful piece of information. I am satisfied that you just shared this helpful information with us. Please stay us up to date like this. Thanks for sharing.

Comments are closed.