Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use foreach with a two dimensional array of objects?

Tags:

c#

object

foreach

This is my try, which doesn't work (I'm a beginner). The idea is to have an simple two dimensional array of Kid.years ints to understand how to use the foreach with objects.

    using System;

        namespace Test
        {
            class Kid
            {
                public int years;
            }
            class Program
            {
                static void Main()
                {
                    Kid[,] array = new Kid[4, 5];
                    for (int counter = 0; counter < 4; counter++)
                    {
                        for (int counter2 = 0; counter2 < 5; counter2++)
                        {
                            array[counter, counter2] = new Kid();
                            array[counter, counter2].years = counter + 1000;
                        }
                    }
                    foreach (int item in array[,].years)
                    {
                        Console.WriteLine(item);
                    }
                }
            }
        }

1 Answers

You can enumerate two dimensional array as below:

foreach (Kid item in array)
{
    Console.WriteLine(item.years);
}   
like image 52
Ramazan Binarbasi Avatar answered Dec 01 '25 16:12

Ramazan Binarbasi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!