1

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.

6
  • 4
    This would be easier to conceptualize if I could see some code. Commented Sep 10, 2013 at 23:26
  • Sure will edit the question but not until tomorrow now thx Commented Sep 10, 2013 at 23:30
  • Arrays in c# implement IEnumerable<T>. What is the problem exactly? See this post for a good description - stackoverflow.com/questions/7173266/… Commented Sep 10, 2013 at 23:32
  • The title of your question is confusing. In C#, multidimensional array (e.g. int[,]) is different from jagged array (e.g. int[][]). From your description, it looks like you're dealing with the former, is that right? Commented Sep 11, 2013 at 0:26
  • @svick you were right, not a jagged array. Commented Sep 11, 2013 at 8:31

1 Answer 1

2

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 ints) and SetValue() to set it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.