Skip to content

Instantly share code, notes, and snippets.

@GeorgeTsiokos
Last active July 19, 2019 19:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GeorgeTsiokos/f1ce4f13406d11e21a0addb3daf25085 to your computer and use it in GitHub Desktop.
Save GeorgeTsiokos/f1ce4f13406d11e21a0addb3daf25085 to your computer and use it in GitHub Desktop.
Enumerable IsOrderedSubsetOf
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