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(), };