How to get distinct entities from a collection using LINQ ?

Dear All,
Many times you have problems like you have a collection which has duplicate entries now you want a LINQ operation which provides you distinct collection as result.
Let start with following example
I have one class which is Contact as declared follow

public class Contacts        {
public string FirstName { get; set; }
public string LastName { get; set; }
public string Phone { get; set; }
}

This class has FirstName, LastName & mobile property.
Now suppose you have following collection

List<Contacts> oContacts = new List<Contacts>() {
new Contacts{ FirstName ="Rajat", LastName="Jaiswal", Phone="123"},
new Contacts{ FirstName ="Sparsh", LastName="Anchaliya", Phone="223"},
new Contacts{ FirstName ="Ajit", LastName="Bagora", Phone="423"},
new Contacts{ FirstName ="Arjun", LastName="Singh", Phone="523"},
new Contacts{ FirstName ="Piyush", LastName="Redwal", Phone="623"},
new Contacts{ FirstName ="Rajat", LastName="Jaiswal", Phone="123"},
new Contacts{ FirstName ="Sparsh", LastName="Anchaliya", Phone="223"},
new Contacts{ FirstName ="Ajit", LastName="Bagora", Phone="423"},
new Contacts{FirstName ="Ajit", LastName="Bagora", Phone="423"},
new Contacts{ FirstName ="Rajat", LastName="Jaiswal", Phone="123"},
new Contacts{ FirstName ="Piyush", LastName="Redwal", Phone="623"},
new Contacts{ FirstName ="Piyush", LastName="Redwal", Phone="623"},
new Contacts{ FirstName ="Arjun", LastName="Singh", Phone="523"},
};

Now the above collection having total 13 contact entities but there is only 5 records which are distinct.
Now you want a LINQ operation which provides only 5 records which are distinct.
To get this we will write following LINQ


List<Contacts> lstContact = oContacts.GroupBy(x => x.FirstName + x.LastName + x.Phone).Select(y => y.First()).ToList<Contacts>() ;

The above LINQ operation will provide you distinct entities.
The logic behind the above statement is very simple we just group by all the columns first and selected first records from that group collection for each group.

I hope you also enjoyed with above LINQ operation as I enjoyed.

Keep Learning
Rajat Jaiswal

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s