Using LINQ's Distinct() on a Specific Property
By Tan Lee Published on Dec 10, 2024 299
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
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:
1 2 3 4 5 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
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
11 Things You Didn't Know About Cloudflare
Dec 19, 2024
Modernize Material UI Admin Dashboard Template
Nov 19, 2024
Base Responsive Material UI Admin Dashboard Template
Nov 18, 2024
Modular Admin Template
Nov 14, 2024