Description
Problem
GroupAdjacent
doesn't let you cheaply compare a small key (e.g. single field) to define groups, then use different selectors for the group key and elements.
For example, consider an IEnumerable
with the following fields:
aKey
a1
a2
a3
b1
b2
b3
You want to efficiently group by aKey
, then use x => A(x.AKey, x.a1, x.a2, x.a3)
as group key and x => B(x.b1, x.b2, x.b3)
as group elements.
One option that works today is GroupAdjacent(x => A(...), x => B(...))
and have a comparer or override Equals
on A
.
The drawback is that one A
instance is generated for every element in the sequence, when you only need a single one per group.
Proposed solution 1
A new overload?
GroupAdjacent(F<X, A> keySelector, F<X, B> elementSelector, F<X, Y> equalitySelector)
Proposed solution 2
GroupAdjacent
doesn't stream its results, it actually buffers each group in a list. Internally these are IList
but only exposed as IEnumerable
.
Exposing the IList
would allow the following solution:
seq.GroupAdjacent(
keySelector: x => x.aKey,
resultSelector: (key, IList elements) => (A(elements[0]), elements.Select(B))
)
Today, this is doable with a cast from IEnumerable
to IList
but it can break with any MoreLINQ release as it relies on an implementation detail.
Alternatively, using elements.First()
instead of elements[0]
will always work but can be quite dangerous if the implementation of GroupAdjacent
becomes non-buffering, as elements
is enumerated twice.
What about non-buffering?
When working with long groups, it'd be interesting to not buffer the groups.
Maybe a new API StreamGroupAdjacent
that has an added constraint that group elements must be consumed in order and only once (but not necessarily fully).
Predicate vs IEqualityComparer
It'd also be nice to have overloads accepting Func<X, X, bool>
instead of IEqualityComparer
.
GroupAdjacent
is relies on adjacency, so uses only equality and never hashes.