Multidimensional vs Jagged array

我只是一个虾纸丫 提交于 2020-04-07 04:52:45

问题


I have used a MultiDimesional Array as follows

  string[,] Columns = { { "clientA", "clientB" }}

    if (Columns.Length != 0)
            {
                for (int i = 0; i < Columns.Length / 2; i++)
                {
                    bulkCopy.ColumnMappings.Add(Columns[i, 0], Columns[i, 1]);
                }
            }

After code analysis I got warning message as

Severity    Code    Description Project File    Line    Suppression State
Warning CA1814  'Order.GetLastOrderID()' uses a multidimensional array of  
'string[,]'. Replace it with a jagged array if possible.    

I have researched jagged arrays on internet but How do I replace my array with jagged array.


回答1:


A jagged array is an array of arrays, so you change your definition to:

string[][] Columns = { new string[] { "clientA", "clientB" }};

Change array access from...

var value = Columns[0,0];

...to...

var value = Columns[0][0];

You also have the option to suppress the warning (right-click on it and select the option you need). According to MSDN, this is a warning that is safe to suppress in certain cases. Check if yours is such a case before you change the code.




回答2:


This should work:

 string[][] Columns = { 
     new string[] { "ClientA", "ClientB" } 
 };

If you need to add more elements to the array, it should look like this:

string[][] Columns = { 
    new string[] { "ClientA", "ClientB" },
    new string[] { "ClientC", "ClientD" },
    new string[] { "ClientE", "ClientF" } 
};

Then you can access each element with the code below

Columns[0][0] // Client A
Columns[0][1] // Client B
Columns[1][0] // Client C
Columns[1][1] // Client D
// etc.


来源:https://stackoverflow.com/questions/41763839/multidimensional-vs-jagged-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!