Click here to Skip to main content
15,887,683 members
Articles / Programming Languages / C# 4.0

LINQ: Enhancing Distinct with the SelectorEqualityComparer

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
15 Apr 2010CPOL 16.2K   4   6
LINQ: Enhancing Distinct with the SelectorEqualityComparer

LINQ With C# (Portuguese)

In my last post, I introduced the PredicateEqualityComparer and a Distinct extension method that receives a predicate to internally create a PredicateEqualityComparer to filter elements.

Using the predicate greatly improves readability, conciseness and expressiveness of the queries, but it can be even better. Most of the times, we don't want to provide a comparison method but just extract the comparison key for the elements.

So, I developed a SelectorEqualityComparer that takes a method that extracts the key value for each element. Something like this:

C#
public class SelectorEqualityComparer<TSource, Tkey> : EqualityComparer<TSource>
    where Tkey : IEquatable<Tkey>
{
    private Func<TSource, Tkey> selector;

    public SelectorEqualityComparer(Func<TSource, Tkey> selector)
        : base()
    {
        this.selector = selector;
    }

    public override bool Equals(TSource x, TSource y)
    {
        Tkey xKey = this.GetKey(x);
        Tkey yKey = this.GetKey(y);

        if (xKey != null)
        {
            return ((yKey != null) && xKey.Equals(yKey));
        }

        return (yKey == null);
    }

    public override int GetHashCode(TSource obj)
    {
        Tkey key = this.GetKey(obj);

        return (key == null) ? 0 : key.GetHashCode();
    }

    public override bool Equals(object obj)
    {
        SelectorEqualityComparer<TSource, Tkey> comparer = 
			obj as SelectorEqualityComparer<TSource, Tkey>;
        return (comparer != null);
    }

    public override int GetHashCode()
    {
        return base.GetType().Name.GetHashCode();
    }

    private Tkey GetKey(TSource obj)
    {
        return (obj == null) ? (Tkey)(object)null : this.selector(obj);
    }
}

Now I can write code like this:

C#
.Distinct(new SelectorEqualityComparer<Source, Key>(x => x.Field))

And, for improved readability, conciseness and expressiveness and support for anonymous types, the corresponding Distinct extension method:

C#
public static IEnumerable<TSource> Distinct<TSource, TKey>
	(this IEnumerable<TSource> source, Func<TSource, TKey> selector)
    where TKey : IEquatable<TKey>
{
    return source.Distinct(new SelectorEqualityComparer<TSource, TKey>(selector));
}

And the query is now written like this:

C#
.Distinct(x => x.Field)

For most usages, it’s simpler than using a predicate.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Paulo Morgado
Portugal Portugal

Comments and Discussions

 
GeneralReadonly Pin
Alexander Batishchev23-Aug-10 5:12
Alexander Batishchev23-Aug-10 5:12 
GeneralRe: Readonly Pin
Paulo Morgado23-Aug-10 5:54
professionalPaulo Morgado23-Aug-10 5:54 
GeneralSame as Pin
Magnus_12-May-10 1:18
Magnus_12-May-10 1:18 
GeneralRe: Same as Pin
Paulo Morgado12-May-10 12:20
professionalPaulo Morgado12-May-10 12:20 
GeneralNice post Pin
J. Dunlap13-Apr-10 12:17
J. Dunlap13-Apr-10 12:17 
GeneralRe: Nice post Pin
Paulo Morgado13-Apr-10 12:33
professionalPaulo Morgado13-Apr-10 12:33 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.