Home  |  Faq  |  Site map  |  Contact
Email sales@ or Call 1-248-686-1424
How to get distinct rows from a list using LINQ:A
Author: Mritunjay Kumar
Date: Nov 8, 2009
How to get distinct rows from a list using LINQ:
 
Think about a situation when records in list are something like below:
 
Here if we use distinct in our select query then it will return all(above 5 records) the employee records.

So, to achieve our requirement we need to use GroupBy like below:
 
List<Employee> DistinctEmployee = AllEmployee
.GroupBy(CurrentEmployee => CurrentEmployee.EmployeeType)
.Select(EmployeeRecords => EmployeeRecords.First())
.ToList();
 
We can also define groups on multiple properties, like below:
 
List<Employee> DistinctEmployee = AllEmployee
.GroupBy(CurrentEmployee => CurrentEmployee.EmployeeType, CurrentEmployee.Name)
.Select(EmployeeRecords => EmployeeRecords.First())
.ToList();
 
There must be other simpler ways to achieve above.

Related Tags:
ASP.NET

top