简体   繁体   English

如何在多维数组中使用键

[英]How to use key in multi-dimensional Array

How to create an array which consists of categories and its sub categories. 如何创建一个由类别及其子类别组成的数组。

Example: 例:

Fruit
  --> Apple
  --> Banana

Car
  --> Civic
  --> Vitz

Drinks
 --> Pepsi
 --> Dew

So it becomes a complete one array. 因此,它成为一个完整的数组。

Note: I don't want to use any collections eg lists,dictionary etc. 注意:我不想使用任何集合,例如列表,字典等。

If you are restricted to using only arrays, then you could do something like: 如果仅限使用数组,则可以执行以下操作:

object[][] arr = new object[3][];
arr[0] = new object[2];
arr[0][0] = "Fruit";
arr[0][1] = new string[2] { "Apple", "Banana" };
arr[1] = new object[2];
arr[1][0] = "Car";
arr[1][1] = new string[2] { "Civic", "Vitz" };
arr[2] = new object[2];
arr[2][0] = "Drinks";
arr[2][1] = new string[2] { "Pepsi", "Dew" };

Then to iterate through: 然后遍历:

for (int i = 0; i < 3; i++)
{
    StringBuilder line = new StringBuilder();
    line.Append((string)arr[i][0] + ": ");
    string[] subs = (string[])arr[i][1];
    for (int j = 0; j < 2; j++)
    {
       line.Append(subs[j] + "; ");
    }
    MessageBox.Show(line.ToString());
}

Note because this uses a jagged array (AKA array of arrays), you can have different numbers of sub-categories. 请注意,因为这使用了锯齿状数组(AKA数组数组),所以可以有不同数量的子类别。 Then to iterate through the sub-categories you would need to use the count. 然后,要遍历子类别,您将需要使用计数。

Create an interface called arrayobject then create the class fruit,car and drinks then implement the interface and make an array of the interface 创建一个名为arrayobject的接口,然后创建类fruit,car和drinks,然后实现该接口并创建该接口的数组

something like 就像是

public interface arrayobject 
{
    string description();
}
class Fruit:arrayobject
{
    public string fruittype;
    public Fruit(string type)
    {
        fruittype = type;
    }

    public string description()
    {
        return fruittype;
    }
}
class Car : arrayobject
{
    public string Cartype;
    public Car(string type)
    {
        Cartype = type;
    }

    public string description()
    {
        return Cartype;
    }
}

now you can make a array of the arrayobject 现在您可以创建arrayobject的数组

arrayobject[] mylist = new arrayobject[2];
mylist[0] = new Fruit("banana");
mylist[1] = new Car("my Ford");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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