How to Remove Duplicate Elements using LINQ Distinct Operator

Waqas Anwar
11 December 2010
16286 Views

If you have a collection (sequence) of objects and you want to remove duplicate entries, you can use LINQ Distinct operator as shown in the following code example.

Following is the Customer objects collection
List<Customer> customers = new List<Customer>();

customers.Add(new Customer { Id = 10, Name = "Simon", Country = "UK" });
customers.Add(new Customer { Id = 11, Name = "Peter", Country = "USA" });
customers.Add(new Customer { Id = 12, Name = "Mark", Country = "UK" });
customers.Add(new Customer { Id = 13, Name = "James", Country = "UK" });
customers.Add(new Customer { Id = 14, Name = "David", Country = "France" });

To get unique set of Countries and to remove duplicate countries (UK) you can use LINQ Distinct operator as follows:
var cities = (from c in customers
              select c.Country).Distinct();

If you will display cities using foreach loop
foreach (var city in cities)
{
   Console.WriteLine(city);
}

You will get following output

UK
USA
France