简体   繁体   中英

C# - how to declare arrays as columns of a 2D array

I'm trying to create a 2D array, with other arrays to represent the columns.

heres what i'm trying to do:

   public int[] item0;
   public int[] item1;
   public int[] item2;
   public int[] item3;
   public int[] item4;
   public int[] item5;
   public int[] item6;
   public int[] item7;
   public int[] item8;
   public int[] item9;

        item0 = new int[22];
        item1 = new int[22];
        item2 = new int[22];
        item3 = new int[22];
        item4 = new int[22];
        item5 = new int[22];
        item6 = new int[22];
        item7 = new int[22];
        item8 = new int[22];
        item9 = new int[22];
        itemList = new int[10,22] { 
{item0}, 
{item1}, 
{item2}, 
{item3}, 
{item4}, 
{item5}, 
{item6}, 
{item7}, 
{item8}, 
{item9} 
};

But I get a console error, telling me that It's not picking up the expected length.

I've looked around at a lot of old questions but they never really clarify how to define an array like this. Any help would be appreciated.

You don't need to do all that in the beginning. A multidimensional array cannot be jagged and automatically makes all inner arrays size 22 if you simply do

itemList = new int[10,22];

Further, you can initialize this like so:

itemList = new int[10,22] {
    {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 16, 17, 18, 19, 20, 21, 22},
    {1, 3, 5, 7, 9 ...

and so on.

You can declare itemList as a "jagged" array:

var itemList = new int[][] {
    item0,
    item1,
    new int[] { 1, 2, 3 },
    new int[] { 1, 2, 3, 4, 5, … },
    item4,
    item5,
    …
};

I've included both references to pre-existing int[] arrays ( item0 , item1 , etc.) as well as in-line array instantiations ( new int[] { … } ) in the above example. Further, note that with jagged arrays, the single array items in itemList do not need to have the same length. This goes to show that a jagged array is not in fact two-dimensional; it is an array of arrays.

看起来您想使用锯齿状的数组,只需要将itemList初始化程序更改为:

var itemList = new int[10][] { item0, item1, item2, item3, item4, item5, item6, item7, item8, item9 };

This should solve your problem

        var itemList = new int[][] {
        item0,
        item1,
        item2,
        item3,
        item4,
        item5,
        item6,
        };

But I recommend you to do it this way

        int[,] itemList = new int[,]
        {
            {1,2,3,4,5 },
            {1,2,3,4,5 },
            {1,2,3,4,5 },
        };

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