I have several numbered lists stored in a List<string>:
List<string> all = new List<string>()
{
"1. Apple",
"2. Banana",
"3. Coconut",
"1. Ant",
"2. Beaver",
"3. Cat"
...
}
I want to split this list into a list of lists where each list contains 1-3.
List<List<string>> split = new List<List<string>>()
{
new List<string>() { "1. Apple", "2. Banana", "3. Coconut"},
new List<string>() { "1. Ant", "2. Beaver", "3. Cat"}
}
There will ALWAYS be “1.” so I can use that as my delimiter. Is there a slick way to do this with LINQ without needing two nested for loops?
Update: I’d like this to be generalized for any length, not always 3.
Just another option to get desired result (assign group index to each item in sequence, then group by that index):
Another option – accumulate results (this will require one traverse over the list)