Last active
July 19, 2019 19:40
-
-
Save GeorgeTsiokos/f1ce4f13406d11e21a0addb3daf25085 to your computer and use it in GitHub Desktop.
Enumerable IsOrderedSubsetOf
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
public static class EnumerableExtensions | |
{ | |
public static bool IsOrderedSubsetOf<T>( | |
this IEnumerable<T> source, | |
IEnumerable<T> target, | |
out T missing, | |
IEqualityComparer<T> equalityComparer = null) | |
{ | |
if (null == equalityComparer) | |
equalityComparer = EqualityComparer<T>.Default; | |
using (var primary = source.GetEnumerator()) | |
using (var secondary = target.GetEnumerator()) | |
{ | |
while (true) | |
{ | |
var moveNext = primary.MoveNext(); | |
if (!moveNext) | |
{ | |
// empty set is always a subset | |
missing = default; | |
return true; | |
} | |
if (!secondary.MoveNext()) | |
{ | |
// we have a value in a, and didn't see it in b | |
missing = primary.Current; | |
return false; | |
} | |
while (!equalityComparer.Equals(primary.Current, secondary.Current)) | |
{ | |
if (secondary.MoveNext()) | |
continue; | |
// we have a value in a, and didn't see it in b | |
missing = primary.Current; | |
return false; | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment