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.Output:
Link to DotNetFiddle example