5.13.2010

Distinct with Func<T,T,bool>

When you go to look for the ability to run a Distinct Linq query using a func and it isn’t there… it causes some confusion.

image

To get around this troublesome omission I had to create my own extension.

I first created my own implementation of IEqualityComparer<T> that will utilize a func to do the equals comparison.

public class FuncEqualityComparer<T> : IEqualityComparer<T>
{
    public FuncEqualityComparer(Func<T, T, bool> func)
    {
        _func = func;
    }

    readonly Func<T, T, bool> _func;

    public bool Equals(T x, T y)
    {
        return _func(x, y);
    }

    public int GetHashCode(T obj)
    {
        return 0;
    }
}

Next I will need an extension method off of IEnumerable<T>.

public static IEnumerable<T> Distinct<T>(this IEnumerable<T> items, Func<T, T, bool> func)
{
    return items.Distinct(new FuncEqualityComparer<T>(func));
}

Now when I check to see what Distinct options are available I see my new Func extension.

image

And to test whether this new distinct is working:

[Test]
public void should_return_distinct_items()
{
    var jedis = new[]
                    {
                        new Jedi {Name = "Mace Windu"},
                        new Jedi {Name = "Mace Windu"},
                        new Jedi {Name = "Luke Skywalker"},
                        new Jedi {Name = "Yoda"},
                        new Jedi {Name = "Yoda"},
                    };

    IEnumerable<Jedi> distinct = jedis.Distinct((j1, j2) => j1.Name == j2.Name);

    distinct.Count().ShouldBe(3);
}

All this code can be found in my Learning Repository –> Learning CSharp solution.

http://github.com/RookieOne/Learning

1 comments:

  1. Great extension method! Very useful!

    Thank you.
    ReplyDelete