Jonathan Birkholz

Distinct With Func

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.

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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.

1
2
3
4
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.

And to test whether this new distinct is working:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[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

C#