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.