未知维数组上的C#循环
我想创建一个扩展方法来循环未知维数组上的C#循环,c#,loops,multidimensional-array,system.array,C#,Loops,Multidimensional Array,System.array,我想创建一个扩展方法来循环System.Array,其维数未知 目前,我使用的是一种天真的方法: 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)
System.Array
,其维数未知
目前,我使用的是一种天真的方法:
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
}
}
publicstaticvoidforeach(此数组源,操作)
{
if(source.Rank==1)
{
for(int w=0;w
我相信,有更优雅的方式来做到这一点。但是我想不出来。如何将该方法推广到无限维数?您可以尝试一种递归方法,在这种方法中,您可以测试数组中的项本身是否是数组。如果项是可iterable,则将调用for循环逻辑,否则您可以对该项执行任何需要执行的操作。如果您的对象实现了ICollection,这应该相当简单。如果您不关心索引,您可以在一个
系统.Array上迭代,而完全不知道它的秩。枚举数将命中每个元素
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);
}
}
}
输出:
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
对于那些在家打球的人来说,这有点混乱,但允许你利用收益率
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);
}
}
可能与@ChristianGollhardt重复使用OOP语言的多维数组“根本错误”是什么?在没有多维数组的情况下,你们希望如何进行张量操作?似乎我误解了你们的问题。我把尺寸和尺寸弄错了@koryakinpI认为zcleghern的意思类似于``公共静态void ForEach(这个数组源,Action Action){if(source.Rank==0){ForEach(源中的var项){Action((T)项);}}}或者{ForEach(源中的数组arr){arr.ForEach(Action);}}}```
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);
}
1
2
3