Created
June 18, 2019 08:26
-
-
Save davidvesely/cc58496d5806d0a4f19ed0b0fa966b79 to your computer and use it in GitHub Desktop.
IEnumerable extensions, Except on different collection type
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Linq; | |
namespace System.Collections.Generic | |
{ | |
public static class IEnumerableExtension | |
{ | |
public static IEnumerable<TFirst> Except<TFirst, TSecond, TCompared>( | |
this IEnumerable<TFirst> first, | |
IEnumerable<TSecond> second, | |
Func<TFirst, TCompared> firstSelect, | |
Func<TSecond, TCompared> secondSelect) | |
{ | |
return Except(first, second, firstSelect, secondSelect, EqualityComparer<TCompared>.Default); | |
} | |
public static IEnumerable<TFirst> Except<TFirst, TSecond, TCompared>( | |
this IEnumerable<TFirst> first, | |
IEnumerable<TSecond> second, | |
Func<TFirst, TCompared> firstSelect, | |
Func<TSecond, TCompared> secondSelect, | |
IEqualityComparer<TCompared> comparer) | |
{ | |
if (first == null) | |
throw new ArgumentNullException("first"); | |
if (second == null) | |
throw new ArgumentNullException("second"); | |
return ExceptIterator(first, second, firstSelect, secondSelect, comparer); | |
} | |
private static IEnumerable<TFirst> ExceptIterator<TFirst, TSecond, TCompared>( | |
IEnumerable<TFirst> first, | |
IEnumerable<TSecond> second, | |
Func<TFirst, TCompared> firstSelect, | |
Func<TSecond, TCompared> secondSelect, | |
IEqualityComparer<TCompared> comparer) | |
{ | |
HashSet<TCompared> set = new HashSet<TCompared>(second.Select(secondSelect), comparer); | |
foreach (TFirst tSource1 in first) | |
if (set.Add(firstSelect(tSource1))) | |
yield return tSource1; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment