Using LINQ's Distinct() on a Specific Property
By Tan Lee Published on Dec 10, 2024 427
Here's an example of how to use LINQ's Distinct() method to filter unique values based on a particular property.
What you need is a 'distinct-by' function. While it's not part of LINQ by default, it's simple to implement yourself.
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) { var keys = new HashSet<TKey>(); foreach (TSource element in source) { // Get the key for the current element TKey key = keySelector(element); // If the key hasn't been seen before, add the element to the result if (keys.Add(key)) { yield return element; } } }
For example:
public class Person { public string Name { get; set; } public int Age { get; set; } }
The DistinctBy()
method is used to filter the people
list by the Name
property, returning only unique names.
internal class Program { static void Main(string[] args) { List<Person> people = new List<Person> { new Person { Name = "Alice", Age = 30 }, new Person { Name = "Bob", Age = 25 }, new Person { Name = "Alice", Age = 30 }, new Person { Name = "Charlie", Age = 35 }, new Person { Name = "Bob", Age = 25 } }; var distinctPeople = people.DistinctBy(p => new { p.Age, p.Name }); foreach (var person in distinctPeople) Console.WriteLine($"{person.Name} - {person.Age}"); } }
People with the same Name
but different Age
are considered duplicates if the name is the same.
These examples demonstrate how to use LINQ's Distinct()
to filter by a particular property, either through DistinctBy()
.
- C# LINQ Tutorial
- C# LINQ query and method syntax
- Group by in LINQ
- How to get the index of an element in C# LINQ
- Cannot use a lambda expression as an argument to a dynamically dispatched operation
- How to group by multiple columns using LINQ
- Using LINQ to remove elements from a List<T>
- How to Find XML element by name with XElement in LINQ
Categories
Popular Posts
Structured Data using FoxLearn.JsonLd
Jun 20, 2025
10 Common Mistakes ASP.NET Developers Should Avoid
Dec 16, 2024
Material Dashboard Admin Template
Nov 17, 2024