Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,690 questions

55,442 answers

573 users

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
...