Making a better Distinct extension for IEnumerable / LINQ

I wasn’t satisfied with the stock “IEnumerable.Distinct()” methods provided by Linq. Typically you would have to make a class that implements “IEqualityOperator” and have a comparison method that determines whether or not two items are equal.

Instead of having to write a custom class to do that, wouldn’t it be nice to just provide a lambda expression? (the answer is yes, it would).

I whipped up this extension method to do just that:

public static IEnumerable<T> Distinct<T>(this IEnumerable<T> source, Func<T, T, bool> equalityComparer)
        var distincts = new List<T>();
        foreach (var item in source)
            var found = false;
            foreach (var d in distincts)
                found = equalityComparer(item, d);
                if (found)

            if (!found)
                yield return item;

And a unit test demonstrating its usage:

    public void DistinctTest()
        var stuff = new int[] { 1, 2, 3, 1, 2, 3, 4, 5, 6, 6 }
            .Select(n => new { Number = n, String = n.ToString() });
        var distinct = stuff.Distinct((x, y) => x.Number == y.Number).ToList();

        Assert.Less(distinct.Count(), stuff.Count());
        foreach(var s in stuff)
            Assert.AreEqual(1, distinct.Where(d => d.Number == s.Number).Count());

Its kind of ugly with the nested ‘for’ loops and tracking which items are already returned, but hey, it works! Enjoy!

Tagged with: , ,
Posted in Programming
One comment on “Making a better Distinct extension for IEnumerable / LINQ
  1. merrill says:

    Hi! Someone in my Facebook group shared this website with us so I came to give it a look. I’m definitely enjoying the information. I’m bookmarking and will be tweeting this to my followers! Outstanding blog and great style and design.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

CodingWithSpike is Jeff Valore. A professional software engineer, focused on JavaScript, Web Development, C# and the Microsoft stack. Jeff is currently a Software Engineer at Virtual Hold Technologies.

I am also a Pluralsight author. Check out my courses!

%d bloggers like this: