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

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,855 questions

51,776 answers

573 users

How to create and use nested Lists (jagged list) in C#

1 Answer

0 votes
using System;
using System.Collections.Generic;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            List<List<int>> list = new List<List<int>>();

            var rand = new Random();
            for (int i = 0; i < 5; i++)
            {
                List<int> sublist = new List<int>();
                int len = rand.Next(1, 13); // sub list size
                for (int j = 0; j < len; j++)
                {
                    sublist.Add(rand.Next(1, 10));
                }
                list.Add(sublist);
            }

            int totalItems = 0;
            foreach (var sublist in list)
            {
                totalItems += sublist.Count;
            }
            Console.WriteLine("total Items:" + totalItems);

            PrintList(list);
        }

        static void PrintList(List<List<int>> list)
        {
            foreach (var sublist in list)
            {
                foreach (var n in sublist)
                {
                    Console.Write(n + " ");
                }
                Console.WriteLine();
            }
        }
    }
}


/*
run:
  
total Items:36
1 5 7 8 1 3
7 2 9 4 2 1 8 2 7 4 5
1 2 2 3
9 2 7 7 8 9 3 9
6 9 3 5 3 5 8
 
*/

 



answered Jan 8, 2017 by avibootz

Related questions

2 answers 374 views
374 views asked Sep 5, 2018 by avibootz
2 answers 218 views
218 views asked Jun 3, 2014 by avibootz
1 answer 116 views
116 views asked Mar 10, 2021 by avibootz
...