How to get unique items from List using Linq in C#

15 May 2014, 08:04 AM

Use the group by clause to get the unique or distinct items from the list because some time Distinct() method does not work for reference type. See the code 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.StudentId).Select(x => x.First());

The result object will contains the list of distinct element by grouping on StudentId primary key of the record. You can use other column too as per your requirement.

Related Contents

15 May 2014, 08:07 AM
C#, LINQ, List
29 Apr 2014, 03:07 AM
C#, Generic
29 Apr 2014, 02:51 AM
C#, Generic
explains How to get Unique or Distinct item from the List using C#

Date Posted 15 May 2014, 07:54 AM
Author Brainy Solutions
Views 5,396