Distinct

As the name suggests and very similar to the SQL world, distinct results in unique or distinct values.

Ever wanted to eliminate duplicates in a list and only get unique values? Distinct will solve your woes. The Distinct method will take a list and remove any duplicates and only produce a unique set of results.

A basic example

Take an array that has as a few duplicates. In the example below, 33 and 11 occur twice. If we use Distinct on the list, it will produce a unique set of results.

Live example: https://dotnetfiddle.net/aJkPba

var scores = new[] {87, 56, 56, 33, 33, 20, 11, 11};

var distinctScores = scores.Distinct();


// output: 87, 56, 33, 20, 11 

Distinct - with objects

Using Distinct on an array of simple types such as ints and strings is possible. But, is it possible with objects? Sort of. You can't per se call Distinct on a list of objects and expect a distinct list of objects. You can, however, apply distinct on a particular property.

In the example below, we find the distinct cities in a list of people.

Live example: https://dotnetfiddle.net/qBkap6

Method syntax

var people = new[]
             {
                 new {Name = "Jennifer", City = "London"},
                 new {Name = "Alton", City = "London"},
                 new {Name = "Adam", City = "Paris"},
                 new {Name = "Milford", City = "New York"},
                 new {Name = "James", City = "Tokyo"},
                 new {Name = "Rachael", City = "Paris"},
             };

var distinctCities = people.Select(p => p.City).Distinct();

//output: London, Paris, New York, Tokyo 

Query syntax

Live example: https://dotnetfiddle.net/BLnuGn

var people = new[]
             {
                 new {Name = "Jennifer", City = "London"},
                 new {Name = "Alton", City = "London"},
                 new {Name = "Adam", City = "Paris"},
                 new {Name = "Milford", City = "New York"},
                 new {Name = "James", City = "Tokyo"},
                 new {Name = "Rachael", City = "Paris"},
             };

var distinctCities = (from p in people
                     select p.City).Distinct();

//output: London, Paris, New York, Tokyo