Looking for help writing a LINQ query on some objects. I feel if my LINQ skills were more ninja I could do this with some clever GroupBy/SelectMany (or something?!).
Stated generically, the question is: given a list of objects in some sort of order, where each object has a Flag, how do I split the list into sub-lists, where each sublist is all of the contiguous points where the flag is set?
An imperative way of doing this would be like the following pseudocode:
foreach object obj
if(obj.FlagSet)
add it to my currentsublist
else
skip to the next obj where FlagSet and start a new sublist
So, given the following input:
{ 1, Flag }, { 2, Flag }, {3, NoFlag }, {4, Flag}, {5, NoFlag}, {6, Flag}…
I’d like the following output:
List 1: {1, 2}
List 2: {4}
List 3: {6}
And I’d like to do it functionally via LINQ. Any ideas?
(I have looked around first, but all the questions I could see appeared to want to either simply group a list or to split into equal sizes, which hasn’t been helpful for me.)
This MSDN article provides code to group by contiguous values:
http://msdn.microsoft.com/en-us/library/cc138361.aspx
I’ve reproduced the code from the link above in case of link-rot:
It’s not pretty, but works well.
In your case it would be something like: