Paulo Morgado

.NET Development & Architecture

This Blog

Syndication

Search

Tags

News

Unit Test Today! Get Typemock Isolator!

Projects

Books

 

Visitors

Visitor Locations

Community

Email Notifications

Archives

Profile

Disclaimer

The opinions and viewpoints expressed in this site are mine and do not necessarily reflect those of Microsoft, my employer or any community that I belong to. Any code or opinions are offered as is. Products or services mentioned are purchased by me, made available to me by my employer or the manufacturer/vendor which doesn't influence my opinion in any way.

LINQ: Enhancing Distinct With The SelectorEqualityComparer
LINQ With C# (Portuguese)

On 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 to extract the comaprison key for the elements.

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

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:

.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:

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:

.Distinct(x => x.Field)

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

Published Fri, Apr 9 2010 2:32 by Paulo Morgado

Filed under: , , , , ,

Comments

# re: LINQ: Enhancing Distinct With The SelectorEqualityComparer@ Thursday, July 15, 2010 8:27 AM

Awesome - I don't know why this isn't included as standard in .NET!

Daniel Skinner

# re: LINQ: Enhancing Distinct With The SelectorEqualityComparer@ Sunday, July 18, 2010 8:10 PM

Thanks, Daniel.

Paulo Morgado

# re: LINQ: Enhancing Distinct With The SelectorEqualityComparer@ Tuesday, July 20, 2010 12:27 AM

Any chance of seeing it being used by a piece of code?

Steve

# re: LINQ: Enhancing Distinct With The SelectorEqualityComparer@ Tuesday, July 20, 2010 2:51 AM

On my previous post I mentioned anounymous types, but you'r right that I didn't provide an example.

var q = from p in products
        join c in categories on p.CategoryId equals c.Id
        select new
        {
            c.Id,
            c.Name
        };
 
var r = from c in q.Distinct(c => c.Id)
        select c;

The longer the property list or harder to compare, the larger is the benefit of this extension method.

Paulo Morgado

Leave a Comment

(required) 
(required) 
(optional)
(required) 
If you can't read this number refresh your screen
Enter the numbers above: