我正在寻找一种将多维数组中的每个值设置为单个值的方法。问题是维数在编译时是未知的 - 它可能是一维的,也可能是 4 维的。自从foreach
不允许你设定价值观,我可以实现这一目标的一种方法是什么?非常感谢。
虽然这个问题表面上看起来很简单,但实际上比看起来更复杂。然而,通过认识到访问多维(甚至锯齿状)数组中的每个位置是一个笛卡尔积运算在数组的索引集上 - 我们可以简化解决方案......并最终编写一个更优雅的解决方案。
我们要利用杠杆Eric Lippert 的 LINQ 笛卡尔积 http://blogs.msdn.com/b/ericlippert/archive/2010/06/28/computing-a-cartesian-product-with-linq.aspx实施来完成繁重的工作。如果您愿意,可以在他的博客上阅读有关其工作原理的更多信息。
虽然此实现特定于访问多维数组的单元格,但应该相对容易了解如何扩展它以访问锯齿状数组。
public static class EnumerableExt
{
// Eric Lippert's Cartesian Product operator...
public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(
this IEnumerable<IEnumerable<T>> sequences)
{
IEnumerable<IEnumerable<T>> emptyProduct =
new[] { Enumerable.Empty<T>() };
return sequences.Aggregate(
emptyProduct,
(accumulator, sequence) =>
from accseq in accumulator
from item in sequence
select accseq.Concat(new[] { item }));
}
}
class MDFill
{
public static void Main()
{
// create an arbitrary multidimensional array
Array mdArray = new int[2,3,4,5];
// create a sequences of sequences representing all of the possible
// index positions of each dimension within the MD-array
var dimensionBounds =
Enumerable.Range(0, mdArray.Rank)
.Select(x => Enumerable.Range(mdArray.GetLowerBound(x),
mdArray.GetUpperBound(x) - mdArray.GetLowerBound(x)+1));
// use the cartesian product to visit every permutation of indexes
// in the MD array and set each position to a specific value...
int someValue = 100;
foreach( var indexSet in dimensionBounds.CartesianProduct() )
{
mdArray.SetValue( someValue, indexSet.ToArray() );
}
}
}
现在,将此代码分解为可重用的方法非常简单,该方法可用于锯齿状或多维数组……或任何可视为矩形数组的数据结构。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)