简体   繁体   中英

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. 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

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[] mylist = new arrayobject[2];
mylist[0] = new Fruit("banana");
mylist[1] = new Car("my Ford");

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