二维数组

时间:2010-12-23 18:31:00

标签: c# multidimensional-array

对于数组中的每个元素,我需要一个唯一的标识符,例如Seat1,Seat2,Seat 3 .......一直到数组长度的末尾。

目前我做了以下事情:

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);
    }
}

这只是在控制台中说“Element False”x 100。

我需要用Seat1,Seat2,Seat3 ....替换“Element”到数组长度的末尾。

任何帮助将不胜感激!

谢谢你!

3 个答案:

答案 0 :(得分:4)

使用ID和Occupied(?)属性创建Seat类(或结构,如果更合适)。制作这种类型的数组。

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" );
}

答案 1 :(得分:0)

  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);
  }

不知道这是什么语言如此idk语法,但只是做一些外部计数器来编号

每次你将每一个都设置为假,不要使用bool,或者写一个类来保存真假和数字信息时,只是说错误

答案 2 :(得分:0)

tvanfosson,我正在努力使你的编码工作,iv把它放到我的主要方法的新课程中,见下文:

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" );
            }
    }
}

这是正确的,因为我似乎收到了很多语法错误

谢谢你!