Using LINQ's Distinct() on a Specific Property

By FoxLearn 12/12/2024 1:08:53 AM   95
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().