假设我有这个功能:
void int Calculate(double[] array) {}
在我的 main 中,我得到了这个数组:
double[,] myArray = new double[3,3];
如何调用 Calculate(...) ?
我尝试(那是不编译):
double[] mySingleArray = myArray[0];
我想避免的是不必要的循环(for)。
我声明了一个常规数组,但如果锯齿状数组或任何其他类型的数组效果更好,它对我来说没问题。
我使用 C# 3.5
最佳答案
首先,让我们像这样声明您的 Calculate() 方法:
int Calculate(IEnumerable<double> doubles)
别担心,您仍然可以将数组传递给该代码。您可能还需要 IList<double>
,但 IEnumerable 10 次中有 9 次就足够了。最主要的是这会让我们使用 yield
以有效方式分割数组的关键字:
public static IEnumerable<T> Slice(this T[,] values)
{
return Slice(values, 0, 0);
}
public static IEnumerable<T> Slice(this T[,] values, int index)
{
return Slice(values, 0, index);
}
public static IEnumerable<T> Slice(this T[,] values, int dimension, int index)
{
int length = values.GetUpperBound(dimension);
int[] point = new int[values.Rank];
point[dimension] = index;
dimension = 1 - dimension;// only works for rank == 2
for (int i = 0; i < length; i++)
{
point[dimension] = i;
yield return (T)values.GetValue(point);
}
}
它仍然需要一些工作,因为它只适用于 2 阶数组,但对于您发布的示例来说应该没问题。
现在您可以像这样调用您的计算函数:
Calculate(myArray.Slice(0));
请注意,由于 IEnumerable 和 yield 语句的工作方式,我发布的代码中的 for 循环基本上是免费的。在您实际迭代计算方法中的项目之前,它不会运行,甚至以“即时”方式运行,以便整个算法保持 O(n)。
当您分享您的 Calculate 方法正在做什么时,它会变得更加有趣。您可以将其表示为简单的聚合 + lambda 表达式。例如,假设您的计算方法返回的项目数 > 5:
myArray.Slice(0).Count(x => x > 5);
或者说它总结了所有项目:
myArray.Slice().Sum();
关于c# 数组函数参数传递一维,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/785767/