Linq By Example

Distinct

Returns the collection as a distinct, non duplicated collection. Similar to using Distinct in SQL.

Basic Distinct

Distinct can be used on simple primitive values to only return unique items.
    
using System;
using System.Collections.Generic;
using System.Linq;

var myList = new List();
myList.Add(1);
myList.Add(1);
myList.Add(2);
Console.WriteLine(string.Join(',', myList)); //Returns 1,1,2


Console.WriteLine(string.Join(',', myList.Distinct())); //Returns 1,2

  

Distinct On Complex Types

Note that the Distinct LINQ method uses the default euality comparer for that type. For primitive types, such as integer, this is as simple as making sure they are the same value. But for complex reference types, as below, it is not that simple as these use the individual reference as the comparer.

In the example below, we add two people to a list, both with the name of "John". Even though our business logic may dictate these are the same people, the default comparer of references say these are different objects. Therefore Distinct returns both items.
    
using System;
using System.Collections.Generic;
using System.Linq;

var myList = new List();
myList.Add(new Person 
{
	Name = "John"
});

myList.Add(new Person 
{
	Name = "John"
});

Console.WriteLine(string.Join(',', myList.Distinct().Select(x => x.Name))); //Returns John, John

public class Person
{
	public string Name {get;set;}
}

  

Overriding Equality Comprarer

In our example below, we have overriden the default comparer and GetHashCode to override how we compare two objects of type Person. This means our Distinct now returns truly distinct People based on our custom code.
    
using System;
using System.Collections.Generic;
using System.Linq;

var myList = new List();
myList.Add(new Person 
{
	Name = "John"
});

myList.Add(new Person 
{
	Name = "John"
});

Console.WriteLine(string.Join(',', myList.Distinct().Select(x => x.Name))); //Returns John, John

public class Person : IEquatable
{
	public string Name {get;set;}
	
	public bool Equals(Person other)
    {
		return this.Name == other.Name;
    }
	
	public override int GetHashCode()
    {
		return Name.GetHashCode();
    }
}