这是一个扩展方法 each
可用于申请 Action<int, int, T>
到每个元素及其对应的二维数组索引:
static public void each<T>(this T[,] a, Action<int, int, T> proc)
{
for (int i = 0; i < a.GetLength(0); i++)
for (int j = 0; j < a.GetLength(1); j++)
proc(i, j, a[i, j]);
}
示例用法:
var arr = new int[3, 3];
arr.each((x, y, val) => arr[x, y] = x + y);
arr.each((x, y, val) => Console.WriteLine("{0} {1} {2}", x, y, val));
是否可以写一个版本each
哪个可以在任何级别的数组上工作?
最佳答案
无法指定具有任意数量参数的泛型,因此您必须向您的过程传递一个索引数组。执行此操作的最简单方法可能是使用递归,因此这是一种递归方法。由于它使用可选参数,因此需要 C# 4.0 或更高版本。
static class Arrays
{
public static void Each<T>(this Array a,
Action<int[], T> proc,
int[] startAt = null)
{
int rank = startAt == null ? 0 : startAt.Length;
int[] indices = new int[rank + 1];
if (rank > 0)
startAt.CopyTo(indices, 0);
for (int i = a.GetLowerBound(rank); i <= a.GetUpperBound(rank); i++)
{
indices[rank] = i;
if (rank == a.Rank - 1)
proc(indices, (T)a.GetValue(indices));
else
Each(a, proc, indices);
}
}
}
你可以这样调用它:
var array = new int[1, 2, 3, 4, 5];
array.Each<int>((indices, data) => array.SetValue(indices.Sum(), indices));
array.Each<int>((indices, data) =>
Console.WriteLine(string.Join(", ", indices) + ": " + data));
关于c# - 通过高阶方法遍历n维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8178763/