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:
pu
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 GetRank(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(2,1,1))
{
Console.WriteLine(item);
}
Output
1
2
3
Full demo here