C# loop over an array of unknown dimensions

multidimensional array in c#
c# 2d array length
how to get row and column length of 2d array in c#

I want to create an extension method to loop over System.Array with unknown number of dimensions

For now I am using a naive approach:

public static void ForEach<T>(this Array source, Action<T> action)
{
    if(source.Rank == 1)
    {
        for (int w = 0; w < source.GetLength(0); w++)
        {
            action((T)source.GetValue(w));
        }
    }
    else if(source.Rank == 2)
    {
        for (int h = 0; h < source.GetLength(1); h++)
        {
            for (int w = 0; w < source.GetLength(0); w++)
            {
                action((T)source.GetValue(h, w));
            }
        }
    }
    else if(source.Rank == 3)
    {
        // etc
    }
}

I am sure, there is much more elegant way of doing that. But I can not figure it out. How do I generalize that method for unlimited number of dimensions ?


If you don't care about the indices, you can just iterate over a System.Array with absolutely no knowledge of its Rank. The enumerator will hit every element.

public class Program
{
    public static void IterateOverArray(System.Array a)
    {
        foreach (var i in a)
        {
            Console.WriteLine(i);
        }
    }

    public static void Main()
    {
        var tests = new System.Array []
        {
            new int[] {1,2,3,4,5,6,7,8},
            new int[,]
            {
                {1,2},{3,4},{5,6},{7,8}
            },
            new int[,,]
            {
                {  {1,2},{3,4} },
                {  {5,6},{7,8} }
            }
        };


        foreach (var t in tests)
        {
            Console.WriteLine("Dumping array with rank {0} to console.", t.Rank);
            IterateOverArray(t);
        }
    }
}

Output:

Dumping array with rank 1 to console.
1
2
3
4
5
6
7
8
Dumping array with rank 2 to console.
1
2
3
4
5
6
7
8
Dumping array with rank 3 to console.
1
2
3
4
5
6
7
8

Link to DotNetFiddle example

Loop over an array of unknown dimension in C#, This example uses the following code to initialize a three-dimensional array and display a textual representation of it. The ArrayTextValue method  The previous post Loop over entries in an array of unknown length in C# explains how to loop over the entries in a one- or two-dimensional array, but what do you do if you don’t know how many dimensions an array has? Admittedly this is an unusual situation, but even in that case you can loop over the values to take action on them.


For those of you playing at home, this is a little messy but allows you to foreach over a Rank taking advantage of yield

public static IEnumerable<T> GetRank<T>(this Array source,int dimension, params int[] indexes )
{

   var indexList = indexes.ToList();
   indexList.Insert(dimension, 0);
   indexes = indexList.ToArray();

   for (var i = 0; i < source.GetLength(dimension); i++)
   {
      indexes[dimension] = i;
      yield return (T)source.GetValue(indexes);
   }
}

Usage

var test1 = new int[2, 2, 3];
test1[1, 1, 0] = 1;
test1[1, 1, 1] = 2;
test1[1, 1, 2] = 3;
foreach (var item in test1.GetRank<int>(2,1,1))
{
  Console.WriteLine(item);
}

Output

1
2
3

Full demo here

Iterate over items in an array with unknown dimensions in C#, Iterate over items in an array with unknown dimensions in C# This example shows how you can iterate over the items in an array that has an unknown number of dimensions. This code gets the array's type object and then uses that object's GetArrayRank method to determine how many dimensions the array has. To iterate efficiently through an array of integers of unknown size in C# is easy. Let’s see how. Firstly, set an array, but do not set the size −. int[] arr = new int[] { 5, 7, 2, 4, 1 }; Now, get the length and iterate through an array using for loop −.


You could try a recursive approach, in which you test if the item in the array is itself an array. The for loop logic will be called if the item is iterable, and otherwise you can operate on the item for whatever you need to do. If your object implements ICollection this should be fairly simple.

How to iterate efficiently through an array of integers of unknown , To iterate efficiently through an array of integers of unknown size in C# is easy. Let's see how. Firstly, set an array, but do not set the size − int[]  This example shows how you can loop over the items in an array with unknown dimensions. It is easier to use a foreach loop to iterate over the items. For example, the following code displays all of the values in the array in the Console window. foreach (string value in values) Console.WriteLine(value);


Arrays in C# - working with arrays in CSharp, In this part of the C# programming tutorial, we will cover arrays. use two for loops to go through all the elements of a two dimensional array. Loop over entries in an array of unknown length in C# Posted on December 13, 2016 by Rod Stephens One way to loop through the items in an array is to hard code its length into the program.


Indexed collections, It has a property for determining the array length and other properties The forEach() method provides another way of iterating over an array: Now the number of dimensions can vary and the size of them can vary too, meaning that the number of loops needed will be variable. So my question is, how do I make this work with e.g. size = [10,15,20,500], where I loop through the first three dimensions, doing calculations on vectors of length = 500?


Interactions in C# Programming: Loops and Arrays, We'll show you how to loop through array values and display them to your users. We have "length" in the example, because you can also use an array's index you much more flexibility when working with unknown data formats. C# Lists. With a loop like this: This makes the assumption that the array is 0-terminated. Since you state that the size of the array is unknown and the numbers are nonzero, that's a somewhat reasonable assumption to make. However, if it doesn't hold true this code will segfault (and/or blow up your computer).