Home > Software engineering >  How does foreach loop works with 2d array?
How does foreach loop works with 2d array?

Time:06-14

Hey guys I'm a newbie in c#. I am trying to build some test programs, I'm building something like a store with cars. I want that only the brands will be shown in my program. But when I write it with foreach loop it takes the second array too... If someone can help me to understand how the foreach loop works it will be perfect :)

class CarsNum
    {
        public const int carsNum = 10;
    }
class CarsBrands : CarsNum
    {
        public string[,] carsBrand = new string[carsNum,carsNum];
        public int carCostArrayInt;
        public void carsBrands()
        {
            carsBrand[0, 0] = "Ford"; carsBrand[0, 1] = "Chevrolet"; carsBrand[0, 2] = "Dodge";
            carsBrand[0, 3] = "Fiat";


            carsBrand[1, 0] = "120,000$"; carsBrand[1, 1] = "100,000$"; carsBrand[1, 2] = "140,000$";
            carsBrand[1, 3] = "50,000$";

            foreach (string i in carsBrand)
            {
                Console.WriteLine(i);
            }
        }
}

CodePudding user response:

You should use for loops for multidimensional arrays.

for (int i = 0; i < carsBrand.GetLength(1); i  )
{
    Console.WriteLine(carsBrand[0,i]);
}

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/multidimensional-arrays

CodePudding user response:

2D string array is not optimal choice for your task ("build a store with car"). c# is object-oriented language, so you can have a class for Car, and a class for Store with list of cars - easy to build, maintain, modify:

public class Car
{
    public string Brand { get; set; }
    public double Price { get; set; }
    public int Year { get; set; } // new Car property
}

public class CarStore
{
    public IList<Car> Cars { get; } = new List<Car>();
}

then use for loop or foreach - both will work

public static void Main()
{
    var store = new CarStore
    {
        Cars = 
        {
            new Car { Brand = "Ford", Year = 2021, Price = 120000 },
            new Car { Brand = "Chevrolet", Year = 2020, Price = 100000 },
        }
    };
    foreach(var car in store.Cars)
    {
        Console.WriteLine(car.Price.ToString("C"));
    }
    // new car arrived:
    store.Cars.Add(new Car { Brand = "Rolls-Royce", Year = 2022, Price = 1_000_000 });
}
  • Related