C#-空数组上的笛卡尔
作者:互联网
我需要6个数组的笛卡尔积-不足之处是在任何时候最多5个数组都可以为空.当所有数组都已填充时,它的效果很好,但是当任何一个数组为null时,它就会炸弹
我的数组是这样的
MatrixArray_1[0] = 1
MatrixArray_1[1] = 2
MatrixArray_2[0] = null
MatrixArray_2[1] = null
MatrixArray_n[0] = 2
MatrixArray_n[1] = 2
等等
我目前正在使用此代码…来自
http://blogs.msdn.com/b/ericlippert/archive/2010/06/28/computing-a-cartesian-product-with-linq.aspx
var product1 = from first in MatrixArray_1
from second in MatrixArray_2
from third in MatrixArray_3
from fourth in MatrixArray_4
from fifth in MatrixArray_5
from sixth in MatrixArray_6
select new[] { first, second, third, fourth, fifth, sixth };
string[][] myCombos_linq = product1.ToArray();
我试过将MatrixArray_n放在第一个!= null处,但会在第一个null数组处停止,并且不会读取所有剩余的数组,因此即使填充了array1和array 3,我的返回数组也始终为0行.
更改代码/逻辑的任何东西,在这一点上,不胜感激!
TIA
解决方法:
由于Eric的方法是使用IEnumerable< IEnumerable< T>> ;,因此您必须执行以下操作:
埃里克(Eric)的代码:
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}));
}
致电地点:
var sequences = new int?[][] { MatrixArray_1, MatrixArray_2, ..., MatrixArray_6 };
var cartesianSequence = sequences.CartesianProduct();
更改通话地点:
var cartesianSequence = sequences.Where(a => a.Any(e => e != null)).CartesianProduct();
Where调用将排除所有元素均为空的序列.
要排除空数组以及仅包含空值的数组:
var cartesianSequence = sequences.Where(a => a != null && a.Any(e => e != null)).CartesianProduct();
或者,通过查询理解:
var filteredSequences =
from sequence in sequences
where sequence != null && sequence.Any(e => e != null)
select sequence
var cartesianSequence = filteredSequences.CartesianProduct();
编辑
另一种可能性是,即使某些元素非空,您也希望排除每个序列的空元素:
var filteredSequences =
from sequence in sequences
where sequence != null && sequence.Any(e => e != null)
select (from v in sequence where v.HasValue select s)
var cartesianSequence = filteredSequences.CartesianProduct();
要么
var cartesianSequence = sequences
.Where(s => s != null && s.Any(e => e != null))
.Select(s => s.Where(v => v != null))
.CartesianProduct();
但是,由于我们不知道您在对结果做些什么,因此很难确切知道该如何建议.
标签:cartesian,linq,arrays,c 来源: https://codeday.me/bug/20191101/1985501.html