How to get distinct rows from a list using LINQ:
Think about a situation when records in list are something like below:
Employee1: EmployeeId=1, Name=”Name1″, EmployeeType=2;
Employee2: EmployeeId=2, Name=”Name2″, EmployeeType=3;
Employee3: EmployeeId=3, Name=”Name3″, EmployeeType=1;
Employee4: EmployeeId=4, Name=”Name4″, EmployeeType=2;
Employee5: EmployeeId=5, Name=”Name5″, EmployeeType=3;
And we want the records of Employee1, Employee2, Employee3 (which are actually distinct according to our requirement for EmployeeType).
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.