简体   繁体   中英

Modify multi Dimensional array

I have an Array variable. I can use the Rank property to get the number of dimensions and I know that you can use a foreach to visit each element as if the array was flattened. However, I wish to modify elements and change element references. I cannot dynamically create the correct number of for loops and I cannot invalidate an enumerator.

EDIT Thanks for the comments, sorry about the previous lack of clarity at the end of a long tiring day. The problem:

private void SetMultiDimensionalArray(Array array)
{
    for (int dimension = 0;  dimension < array.Rank;   dimension++)
    {
        var len = array.GetLength(dimension);
        for (int k = 0; k < len; k++)
        {
            //TODO: do something to get/set values
        }
     }
}

Array array = new string[4, 5, 6];
SetMultiDimensionalArray(array);
Array array = new string[2, 3];
SetMultiDimensionalArray(array);

I had another look before reading this page and it appears all I need to do is create a list of integer arrays and use the overloads of GetValue and SetValue -

Array.GetValue(params int[] indices)
Array.SetValue(object value, params int[] indices)

Everything seems clear now unless someone can suggest a superior method. svick has linked to this so I will accept this answer barring any further suggestions.

It's hard to tell what exactly do you need, because your question is quite unclear.

But if you have a multidimensional array (not jagged array) whose rank you know only at runtime, you can use GetValue() to get the value at specified indices (given as an array of int s) and SetValue() to set it.

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