add GroupUntil extension

This commit is contained in:
ig 2023-05-04 09:42:57 +02:00
parent e869c1e2fc
commit 4b510f6448
1 changed files with 43 additions and 0 deletions

View File

@ -68,6 +68,8 @@ public static class EnumerableUtils
// }
public static Queue<T> ToQueue<T>(this IEnumerable<T> ts)
{
var q = new Queue<T>();
@ -141,6 +143,7 @@ public static class EnumerableUtils
}
}
public static IEnumerable<(T left, T right)> Pairwise<T>(this IEnumerable<T> ts, T seed)
{
using var e = ts.GetEnumerator();
@ -363,6 +366,46 @@ public static class EnumerableUtils
}
[SuppressMessage("ReSharper", "AccessToDisposedClosure")]
public static IEnumerable<IEnumerable<T>> GroupUntil<T>(this IEnumerable<T> sequence, Func<T, T, Boolean> splitBetween)
{
using var e = sequence.GetEnumerator();
if(!e.MoveNext())
yield break; // empty sequence
var moreInSeq = false;
var moreInGroup = false;
do
{
yield return GetGroup();
while (moreInGroup)
MoveNext();
}
while (moreInSeq);
void MoveNext()
{
var prev = e.Current;
moreInSeq = e.MoveNext();
moreInGroup = moreInSeq && !splitBetween(prev, e.Current);
}
IEnumerable<T> GetGroup()
{
do
{
yield return e.Current;
MoveNext();
}
while (moreInGroup);
}
}
public static IEnumerable<T> NotNull<T>(this IEnumerable<T?> ts)
{
return ts.Where(t => t != null)!;