Summary: in this tutorial, you’ll learn how to use the LINQ Distinct()
method to return distinct elements of a sequence.
Introduction to the LINQ Distinct() method
LINQ Distinct()
is an extension method that returns unique elements from a sequence:
IEnumerable<TSource> Distinct<TSource>(
this IEnumerable<TSource> source
)
Code language: C# (cs)
In this syntax:
TSource
is the type of element of the input sequence.source
is the input sequence.
The Distinct()
method returns an IEnumerable<T>
object that contains distinct elements of the source sequence. Note that the result is an unordered sequence.
The Distinct()
method uses a default equality comparer to identify unique elements in the sequence. If you want to use a custom equality comparer, you can use the following overload of the Distinct()
method:
IEnumerable<TSource> Distinct<TSource>(
this IEnumerable<TSource> source,
IEqualityComparer<TSource>? comparer
);
Code language: C# (cs)
In this syntax, you pass an equality comparer to the Distinct()
method to compare two elements to identify the distinction.
LINQ Distinct() method examples
Let’s take some examples of using the LINQ Distinct()
method.
1) Using LINQ Distinct() method to get a sequence of unique numbers
The following program demonstrates how to use the LINQ Distinct()
method to get a sequence of unique numbers from an array of integers.
using static System.Console;
int[] scores = { 1, 2, 2, 3, 4, 4, 5 };
var uniqueScores = scores.Distinct();
foreach (var score in uniqueScores)
{
Write($"{score} ");
}
Code language: C# (cs)
Output:
1 2 3 4 5
Code language: C# (cs)
How it works.
First, declare and initialize the scores array with seven integers:
int[] scores = { 1, 2, 2, 3, 4, 4, 5 };
Code language: C# (cs)
Second, use Distinct()
method to return a new sequence that contains only unique numbers from the scores array. In this case, it returns {1,2,3,4,5}
:
var uniqueScores = scores.Distinct();
Code language: C# (cs)
Third, write each number in the uniqueScores
to the console using a foreach
loop and Write()
method:
foreach (var score in uniqueScores)
{
Write($"{score} ");
}
Code language: C# (cs)
2) Using LINQ Distinct() method to get a sequence of the unique strings
The following program demonstrates how to use the Distinct()
method to return unique string values from an array of the most popular oceans:
using static System.Console;
string[] oceans = {
"Pacific",
"Atlantic",
"Indian",
"Southern",
"Arctic",
"Atlantic", // duplicate
"Pacific" // duplicate
};
var uniqueOceans = oceans.Distinct();
foreach (string ocean in uniqueOceans)
{
WriteLine(ocean);
}
Code language: C# (cs)
Output:
Pacific
Atlantic
Indian
Southern
Arctic
Code language: C# (cs)
How it works.
First, declare an array of strings called oceans that contains the most popular oceans. The array contains the duplicate values of “Atlantic” and “Pacific”.
Second, use the Distinct()
method to return a new sequence that contains only unique string values from the oceans array.
Third, write each string value in the oceans sequence to the console using a foreach
loop and WriteLine
method.
3) Using LINQ Distinct() method to return a sequence of unique objects
The following program demonstrates how to use the Distinct()
method to retrieve unique products from a list of products:
using static System.Console;
class Product
{
public int? Id { get; set; }
public string? Name { get; set; }
public decimal? Price { get; set; }
public override string ToString()
{
return $"{Id} {Name} {Price:C}";
}
}
// Define a custom ProductComparer class that compares
// Product objects based on their id
class ProductComparer : IEqualityComparer<Product>
{
public bool Equals(Product? x, Product? y)
{
// Check for null values
if (x == null || y == null)
return false;
// Check if the two Product objects are the same reference
if (ReferenceEquals(x, y))
return true;
// Compare the Id of the two Product objects
// to determine if they're the same
return x.Id == y.Id;
}
public int GetHashCode(Product? obj)
{
if (obj == null || obj.Id == null)
return 0;
return obj.Id.GetHashCode();
}
}
class Program
{
static void Main(string[] args)
{
// Create a List of Product objects
List<Product> products = new() {
new Product { Id =1, Name = "A", Price=9.99M },
new Product { Id =2, Name = "B", Price=15.99M },
new Product { Id =3, Name = "C", Price=5.99M },
new Product { Id =1, Name = "A", Price=9.99M },
new Product { Id =2, Name = "B", Price=15.99M },
};
var uniqueProducts = products.Distinct(new ProductComparer());
foreach (var product in uniqueProducts)
{
WriteLine(product);
}
}
}
Code language: C# (cs)
Output:
1 A $9.99
2 B $15.99
3 C $5.99
Code language: C# (cs)
How it works.
First, define a Product
class that has three properties Id, Name, and Price.
Next, define the ProductComparer
that compares two products and returns true if two products have the same id.
Then, create a new list of products with five Product objects. Notice that the list contains duplicate Product
objects.
After that, retrieve unique Product objects from the list using the Distinct()
method. The Distinct()
method uses a ProductComparer
object to identify the unique products.
Finally, write each product to the console using a foreach
loop and the Writeline
method.
Summary
- Use the LINQ
Distinct()
method to retrieve unique elements of a sequence.