Saturday, March 10, 2012

Select Distinct Using Linq

Problem:
              We have a list and when want to filter the list based on property to get the unique List.  

Solution:
               The solution to the above problem is very simple, as we have list and we want to get the distinct list based on some property of that list.For this code which I have used is listed in List 1 here you can see that i have an Employee class which has employee id, name and city properties, then in the main function I have declare _employeeList of type list and added records in the list. Here you can see that I have named employees with Employee A, Employee B and so on. You can see that I have place Employee A , Employee B and Employee C are duplicate and in cities I have used Islamabad, Lahore and Karachi.

List 1

Here I have get the distinct list based on two property first the name of the employee and then the based on the city. You can see in the statement where I have distinct employee list, I have first used the GroupBy of the linq and here you can notice that I have group by name of the employee as I want to get the list of unique name of the employee after the group by is the the select of the linq to get the first record of the grouped list.
Image 1
After getting the distinct employee list in var type I have used the foreach loop to display the distinct employee based on the employee name and you can see in the output that it shows only 6 records as Employee A, Employee B and Employee C has two records each so one is selected and shown. 
In the next distinct statement I have used the city , so that the resultant record are distinct on the city name and in the Image 1 you can see both the outputs.First is the distinct based on employee name and has 6 records and second is the distinct based on city and has only 3 records.
This was the way I get the distinct list based on property of the object and hope if you have similar problem then you can solve your problem by using above technique.

All and any comments / bugs / suggestions are welcomed!