The easiest way of getting unique items from list is LINQ’s Distinct() method. In this article you’ll see how to use it with both built-in types (like collection of integers) and custom types (like collection of complex type objects).
Get unique values from collection of integers
Let’s start with creating example list of items where some of them are duplicates.
|
var duplicatedItems = new List<int>() { 1, 1, 2, 3, 3, 4, 5, 5, 5 };
|
Now we can use Distinct function to get collection of unique items from above list.
|
var uniqueItems = duplicatedItems.Distinct();
|
Print newly created collection to screen using foreach loop.
|
foreach (var item in duplicatedItems)
{
Console.WriteLine(item);
}
|
Result:
Get unique values from collection of custom objects
Let’s start with creating custom class. For the purpose of this example it’ll be Person class containing two properties: Forename and Surname.
|
public class Person
{
public string Forename { get; set; }
public string Surname { get; set; }
}
|
Distinct method builds unique collection by comparing items. As a result of what we need to define custom comparer, which defines when we can say that two Person objects are the same. In our case such objects are equal when both forename and surname are equal.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public class PersonEqualityComparer : IEqualityComparer<Person>
{
public bool Equals(Person x, Person y)
{
return x.Forename == y.Forename && x.Surname == y.Surname;
}
public int GetHashCode(Person obj)
{
int forenameHash = obj.Forename.GetHashCode();
int surnameHash = obj.Surname.GetHashCode();
return forenameHash ^ surnameHash;
}
}
|
As a next step we prepare example collection of items. As you can see below some of them are duplicated.
|
var duplicatedItems = new List<Person>();
duplicatedItems.Add(new Person() { Forename = “John”, Surname = “Smith” });
duplicatedItems.Add(new Person() { Forename = “Michael”, Surname = “Jones” });
duplicatedItems.Add(new Person() { Forename = “Olivia”, Surname = “Taylor” });
duplicatedItems.Add(new Person() { Forename = “Olivia”, Surname = “Taylor” });
duplicatedItems.Add(new Person() { Forename = “John”, Surname = “Smith” });
duplicatedItems.Add(new Person() { Forename = “Olivia”, Surname = “Taylor” });
|
Now we’re ready to call Distinct method. This time it gets a parameter which is previously defined equality comparer. Unique collection is stored within uniqueItems variable and listed with foreach loop.
|
var comparer = new PersonEqualityComparer();
var uniqueItems = duplicatedItems.Distinct(comparer);
foreach (var item in uniqueItems)
{
Console.WriteLine(item.Forename + ” “ + item.Surname);
}
|
Result:
|
John Smith
Michael Jones
Olivia Taylor
|