How to get repeating items only from List using Linq in C#

15 May 2014, 08:18 AM

Use the group by clause to identify the repeating elements in the list. 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"},
                                   new Student(){StudentId=2,StudentName = "Student 2"}
                                };


 var result = strList.GroupBy(x => x.StudentId).SelectMany(x => x.Skip(1).Take(1));

You can also use where clause for same achieving same result.

 var result = strList.GroupBy(x => x.StudentId)
                     .Where(x=>x.Count()>1).Select(x => x.First());

Related Contents

15 May 2014, 07:54 AM
C#, LINQ, List
29 Apr 2014, 03:07 AM
C#, Generic
29 Apr 2014, 02:51 AM
C#, Generic
About
Explains How to get Duplicate or Repeating items only from List using Linq in C#

Date Posted 15 May 2014, 08:07 AM
Author Brainy Solutions
Views 1,093
;