I’d like a method that would split an IEnumerable at a predicate, grouping items together by their index relative to the predicate. For example, it could split a List<string> at items satisfying x => MyRegex.Match(x).Success, with items “in between” such matches being grouped together.
Its signature could look something line
public static IEnumerable<IEnumerable<TSource>> Split<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> predicate,
int bool count
)
, possibly with an extra element of the output containing all of the dividers.
Is there a more efficient and/or compact way to implement this than a foreach loop? I feel like it should be possible to implement with LINQ methods, but I can’t put my finger on it.
Example:
string[] arr = {"One", "Two", "Three", "Nine", "Four", "Seven", "Five"};
arr.Split(x => x.EndsWith("e"));
Either of the following would be OK:
IEnumerable<string> {{}, {"Two"}, {}, {"Four", "Seven"}, {}}
IEnumerable<string> {{"Two"}, {"Four", "Seven"}}
the optional element for storing matches would be {"One", "Three", "Nine", "Five"}.
You should do this through an extension method (this method assumes you ignore the partitioned item):