How to split a list into sublists (list of lists) by checking a condition on elements in C#

1 Answer

0 votes
using System;
using System.Linq;
using System.Collections.Generic;
                      
public class Program
{
    public static void Main()
    {
        List<int> lst = new List<int>() { 1, 2, 3, 0, 4, 5, 6, 7, 0, 8, 9, 10 };
        var list_of_lists_by_zero = lst.Aggregate(new List<List<int>>{new List<int>()},
                                   (list, value) => {
                                       list.Last().Add(value);
                                       if (value == 0) list.Add(new List<int>());
                                       return list;
                                   });
 
        foreach (List<int> subList in list_of_lists_by_zero) {
            foreach (int elements in subList) {
                Console.WriteLine(elements);
            }
            Console.WriteLine();
        }
    }
}
  
  
  
/*
run:
  
1
2
3
0

4
5
6
7
0

8
9
10
  
*/

 



answered Mar 10, 2021 by avibootz
edited Mar 10, 2021 by avibootz
...