【发布时间】:2010-12-10 07:45:16
【问题描述】:
SDK 向我返回了一个具有多个维度的数组,例如:
int[,,] theArray = new int[2,8,12];
我需要访问数组中的每个元素并返回值和值的位置。我需要在不知道传入数组的维数和元素数的情况下执行此操作。
【问题讨论】:
-
这是家庭作业吗?
标签: c# arrays multidimensional-array loops
SDK 向我返回了一个具有多个维度的数组,例如:
int[,,] theArray = new int[2,8,12];
我需要访问数组中的每个元素并返回值和值的位置。我需要在不知道传入数组的维数和元素数的情况下执行此操作。
【问题讨论】:
标签: c# arrays multidimensional-array loops
使用 for 循环:
for (int i=theArray.GetLowerBound(0);i<=theArray.GetUpperBound(0);++i)
{
for (int j=theArray.GetLowerBound(1);j<=theArray.GetUpperBound(1);++j)
{
for (int k=theArray.GetLowerBound(2);k<=theArray.GetUpperBound(2);++k)
{
// do work, using index theArray[i,j,k]
}
}
}
如果事先不知道维数,可以使用Array.Rank来确定。
【讨论】:
这样的东西对你有用吗?它递归排名,因此您可以使用 foreach() 并获取包含当前项目索引的数组。
class Program
{
static void Main(string[] args)
{
int[, ,] theArray = new int[2, 8, 12];
theArray[0, 0, 1] = 99;
theArray[0, 1, 0] = 199;
theArray[1, 0, 0] = 299;
Walker w = new Walker(theArray);
foreach (int i in w)
{
Console.WriteLine("Item[{0},{1},{2}] = {3}", w.Pos[0], w.Pos[1], w.Pos[2], i);
}
Console.ReadKey();
}
public class Walker : IEnumerable<int>
{
public Array Data { get; private set; }
public int[] Pos { get; private set; }
public Walker(Array array)
{
this.Data = array;
this.Pos = new int[array.Rank];
}
public IEnumerator<int> GetEnumerator()
{
return this.RecurseRank(0);
}
private IEnumerator<int> RecurseRank(int rank)
{
for (int i = this.Data.GetLowerBound(rank); i <= this.Data.GetUpperBound(rank); ++i)
{
this.Pos.SetValue(i, rank);
if (rank < this.Pos.Length - 1)
{
IEnumerator<int> e = this.RecurseRank(rank + 1);
while (e.MoveNext())
{
yield return e.Current;
}
}
else
{
yield return (int)this.Data.GetValue(this.Pos);
}
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.RecurseRank(0);
}
}
}
【讨论】:
我不确定我是否理解您关于“返回位置[n,n,n]”的问题,但是如果您尝试从一个方法返回多个值,那么有几种方法可以做到这一点。
• 使用out 或引用参数(例如Int),这些参数在从方法返回之前设置为返回值。
• 传入一个数组,例如,一个由三个整数组成的数组,其元素在方法返回之前由方法设置。
• 返回一个值数组,例如,一个由三个整数组成的数组。
【讨论】: