Find duplicate with Linq - Online Free Computer Tutorials.

'Software Development, Games Development, Mobile Development, iOS Development, Android Development, Window Phone Development. Dot Net, Window Services,WCF Services, Web Services, MVC, MySQL, SQL Server and Oracle Tutorials, Articles and their Resources

Saturday, May 28, 2011

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.
[sourcecode language="csharp"]
SELECT email,
COUNT(email) AS NumOccurrences
FROM users
GROUP BY email
HAVING ( COUNT(email) > 1 )

[/sourcecode]
Linq query work same as on the set of collection and which make use of count

[sourcecode language="csharp"]
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);
[/sourcecode]

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

No comments:

Post a Comment