How to get count of repeating or Duplicate objects in List using Linq C#

25 Apr 2014, 07:40 AM

Use the group by clause and set the field name you want to group data and in the select method get group by key and items count. See the example below

 

 List<Student> strList = new List<Student>()
                                       {
                                           new Student(){StudentId=1,StudentName = "Student 1"},
                                           new Student(){StudentId=2,StudentName = "Student 2"},
                                           new Student(){StudentId=1,StudentName = "Student 1"},
                                           new Student(){StudentId=3,StudentName = "Student 3"},
                                           new Student(){StudentId=2,StudentName = "Student 2"}
                                       };


 var result = strList.GroupBy(x => x.StudentName).Select(x => new { 
                                                                     Name = x.Key, 
                                                                     Total = x.Count() 
                                                                     });

You can also get it using the query expression.

 var result2 = from s in strList
               group s by s.StudentName into groupValue
               select new
                        {
                            Email = groupValue.Key ,
                            Total = groupValue.Count(),
                        };

Related Contents

15 May 2014, 08:07 AM
C#, LINQ, List
15 May 2014, 07:54 AM
C#, LINQ, List
29 Apr 2014, 03:07 AM
C#, Generic
About
Explains how to get count of repeating or duplicate objects in List using group by clause of Linq C#

Date Posted 25 Apr 2014, 07:30 AM
Author Brainy Solutions
Views 6,715
;