[Fork] https://stackoverflow.com/questions/77539127/what-is-the-idiomatic-way-to-populate-a-list-of-lists-in-c

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
using System.Linq;

//https://stackoverflow.com/questions/77539127/what-is-the-idiomatic-way-to-populate-a-list-of-lists-in-c

using NUnit.Framework; // Throws NUnit.Framework.AssertionException

    public struct Bar
    {
        public float val;

        public Bar(float val) {  this.val = val; }  
    }

    internal class Program
    {
        public static void Main(string[] args)
        {
            int rows = 3;
            int cols = 4;

            List<List<Bar>> mat = Enumerable.Repeat(
                   Enumerable.Repeat(default(Bar), cols).ToList(),
                   rows
               ).ToList();
            
			Assert.That(mat.All(row => object.ReferenceEquals(row, mat[0]))); // Does not throw.
			
            foreach(var i in Enumerable.Range(0, rows * cols))
            {
                int row = i / cols;
                int col = i % cols;
                mat[row][col] = new Bar((float)i);
            }

            foreach (var row in Enumerable.Range(0, rows))
            {
                foreach (var col in Enumerable.Range(0, cols))
                {
                    Console.Write(mat[row][col].val + " ");
                }
                Console.Write("\n");
            }
        }
    }
;