Linq/C#: How to split List into variable length chunks based on list item information?

I am trying to split up a list of type Record in Linq into sub lists based on certain Type information. There is always one record with type "a" before and one with type "b" after each group of records. I have a class Record:

class Record
{
    public string Type { get; set; }
    public string SomeOtherInformation { get; set; }
}

Here is a sample list (List<Record> records):

Type    SomeOtherInformation
a       ......
x       ......
x       ......
b       ......
a       ......
b       ......
a       ......
x       ......
x       ......
x       ......
x       ......
x       ......
b       ......

The desired output is (List<List<Record>> lists):

List #1:        List #2:        List #3:
a       ......  a       ......  a       ......
x       ......  b       ......  x       ......
x       ......                  x       ......
b       ......                  x       ......
                                x       ......
                                x       ......
                                b       ......

I am currently going through this list with a for loop and create a new list whenever the type is "a" and add it to the sub-list list when an item's type is "b". I am wondering if there is a better way to to this with Linq. Can this be done with Linq, if so, how?

Jon Skeet
people
quotationmark

You can't cleanly do this with normal LINQ, as far as I'm aware. The streaming operators within LINQ rely on you being able to make a decision about an item (e.g. whether or not to filter it, how to project it, how to group it) based on just that item, and possibly its index within the original source. In your case, you really need more information than that - you need to know how many b items you've already seen.

You could do it like this:

int bs = 0;
var groups = records.GroupBy(item => item.Type == 'b' ? bs++ : bs,
                             (key, group) => group.ToList())
                    .ToList();

However, that relies on the side-effect of b++ within the grouping projection (to keep track of how many b items we've already seen) - it's definitely not idiomatic LINQ, and I wouldn't recommend it.

people

See more on this question at Stackoverflow