How to get elements from List which is not repeating using C#

15 May 2014, 08:29 AM

Use the group by clause and check count for each group. If group count is one, its mean it has no repeating record. See example below.

 var 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)
                     .Where(x => x.Count() == 1).Select(x => x.First());


The above example returns only “Student 3” record which is not repeating.

Related Contents

About
Explains how to get those elements that are not duplicate and only has single occurrence in c# using Linq.

Date Posted 15 May 2014, 08:23 AM
Author Brainy Solutions
Views 1,267
;