简体   繁体   中英

2 dimensional array

For each element in the array I need a unique identifier such as Seat1, Seat2, Seat 3....... all the way to the end of the length of the array.

currently I have done the following:

int rows = 10, cols = 10;
bool[ , ] seatArray = new bool[rows , cols]; //10 rows, 10 collums

for (int i = 0; i < rows; i++)
    for (int j = 0; j < cols; j++ )
    {
        seatArray[i, j] = false;
    }

    foreach (bool element in seatArray)
    {
        Console.WriteLine("element {0}", element);
    }
}

this simply just says "Element False" x 100 in the console.

i need to replace "Element" with Seat1, Seat2, Seat3....to the end of the array length.

any help will be much appreciated!

thank you!

Create a Seat class (or structure, if more appropriate) with ID and Occupied(?) properties. Make an array of this type.

public class Seat
{
    public string ID { get; set; }
    public bool Occupied { get; set; }
}

int rows = 10, cols = 10;
Seat[,] seats = new Seat[rows,cols];

for (int i = 0; i < rows; ++i )
{
    for (int j = 0; j < cols; ++j)
    {
         seats[i,j] = new Seat { ID = "Seat" + (i*cols + j), Occupied = false };
    }
}

foreach (var seat in seats)
{
    Console.WriteLine( "{0} is{1} occupied", seat.ID, seat.Occupied ? "" : " not" );
}
  int count = 1;

for (int i = 0; i < rows; i++)
  for (int j = 0; j < cols; j++ )
  {
    seatArray[i, j] = count;
    count++;
  }

  foreach (bool element in seatArray)
  {
    Console.WriteLine("element {0}", element);
  }

no idea what language this is so idk the syntax but just do some external counter to number them

that just says false every time you set every one to false, dont use a bool, or write a class to hold the true false and number info

tvanfosson, i am struggling to make your coding work, iv put it into a new class off my main method see below:

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

namespace ConsoleApplication2
{
    class Class1
    {
        public class Seat
            {
                public string ID { get; set; }
                public bool Occupied { get; set; }
            }

            int rows = 10, cols = 10;
            Seat[,] seats = new Seat[rows,cols];

            for (int i = 0; i < rows; ++i )
            {
                for (int j = 0; j < cols; ++j)
                {
                     seats[i,j] = new Seat { ID = "Seat" + (i*cols + j), Occupied = false };
                }
            }

            foreach (var seat in seats)
            {
                Console.WriteLine( "{0} is{1} occupied", seat.ID, seat.Occupied ? "" : " not" );
            }
    }
}

is this correct as i seem to be receiving a lot of syntax errors

thank you!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM