Skip to content

Instantly share code, notes, and snippets.

@DrEsteban
Last active July 18, 2019 23:28
Show Gist options
  • Save DrEsteban/7764e89754e2d239d955197c3cef1f32 to your computer and use it in GitHub Desktop.
Save DrEsteban/7764e89754e2d239d955197c3cef1f32 to your computer and use it in GitHub Desktop.
/// <summary>
/// Returns an enumerable that excludes elements from the second enumerable where the key selectors produce a match
/// </summary>
public static IEnumerable<X> Except<X, Y, Z>(this IEnumerable<X> first, IEnumerable<Y> second, Func<X, Z> firstSelector, Func<Y, Z> secondSelector, IEqualityComparer<Z> equalityComparer = null)
{
    ILookup<Z, Y> secondLookup;
    if (equalityComparer == null)
    {
        secondLookup = second.ToLookup(s => secondSelector(s));
    }
    else
    {
        secondLookup = second.ToLookup(s => secondSelector(s), equalityComparer);
    }
    return first.Where(f => !secondLookup.Contains(firstSelector(f)));
}

/// <summary>
/// Returns an enumerable that excludes elements from the second enumerable where the key selectors produce a match
/// </summary>
public static IEnumerable<X> Except<X, Y>(this IEnumerable<X> first, IEnumerable<Y> second, Func<Y, X> secondSelector, IEqualityComparer<X> equalityComparer = null)
{
    return Except(first, second, f => f, secondSelector, equalityComparer);
}

/// <summary>
/// Returns an enumerable that excludes elements from the second enumerable where the key selectors produce a match
/// </summary>
public static IEnumerable<X> Except<X, Y>(this IEnumerable<X> first, IEnumerable<Y> second, Func<X, Y> firstSelector, IEqualityComparer<Y> equalityComparer = null)
{
    return Except(first, second, firstSelector, s => s, equalityComparer);
}

----------------------------

var foo = new char[] { 'a', 'b', 'c' };
var bar = new string[] { "A", "b", "c" };
bar.Except(foo, f => f.ToString())
> ["A"]
bar.Except(foo, f => f.ToString(), StringComparer.OrdinalIgnoreCase)
> []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment