DistinctBy<T>

Given a complex object type, select distinct instances based on a specific property (based on ICompareEquality) or function.


Reference: http://stackoverflow.com/questions/489258/linq-distinct-on-a-particular-property
Language:
C#
Keywords:
Code Snippet

/// <see cref="http://stackoverflow.com/questions/489258/linq-distinct-on-a-particular-property" />

public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)

{

    HashSet<TKey> seenKeys = new HashSet<TKey>();

    foreach (TSource element in source)

    {

        if (seenKeys.Add(keySelector(element)))

        {

            yield return element;

        }

    }

}

Example

// GetFiles is using an overload to include subdirectories. DistinctBy Name (NOT by FullName)
// ensures that no two files with the same name (from different directories) would be returned.

new
DirectoryInfo(@"C:\", SearchOption.AllDirectories).GetFiles(@"*.xls").DistinctBy(fi => fi.Name);


Created 2012-08-22
comments powered by Disqus
Login