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.