This question already has an answer here:
- linq group by contiguous blocks 5 answers
Lets say I have an list of strings with the following values:
["a","a","b","a","a","a","c","c"]
I want to execute a linq query that will group into 4 groups:
Group 1: ["a","a"] Group 2: ["b"] Group 3: ["a","a","a"] Group 4: ["c","c"]
Basically I want to create 2 different groups for the value "a" because they are not coming from the same "index sequence".
Anyone has a LINQ solution for this?
You just need key other than items of array
Here is the result: Link
Calculate the "index sequence" first, then do your group.
Using an extension method based on the APL scan operator, that is like
Aggregate
but returns intermediate results paired with source values:You can create extension methods for grouping by consistent runs:
And using the simplest version, you can get either an
IEnumerable<IGrouping>>
:Or a version that dumps the
IGrouping
(and itsKey
) for anIEnumerable
:This is a naive
foreach
implementation where whole dataset ends up in memory (probably not an issue for you since you doGroupBy
):Here comes a slightly complicated implementation with
foreach
andyield return
enumerator state machine which keeps only current group in memory - this is probably how this would be implemented on framework level:EDIT: This is apparently also the way MoreLINQ does it.
And this is a joke version using LINQ only, it is basically the same as the first one but is slightly harder to understand (especially since
Aggregate
is not the most frequently used LINQ method):