我需要创建一组列表的笛卡尔积。例如,我有:
{ {4,3,7}, {1,2,9}, {5,8} }
我需要得到: {4,1,5}, {4,1,8}, {3,1,5}, {3,1,8}, ... , {7,9,8}
目前我已经学习到,可以使用类似以下代码来实现:
var lists = new List<List<int>>
{
new List<int> { 4, 3, 7},
new List<int> { 1, 2, 9},
new List<int> { 5, 8},
};
IEnumerable<IEnumerable<int>> empty = new[] { Enumerable.Empty<int>() };
var agg = lists.Aggregate(
empty,
(acc, next)
=>
(from ac in acc
from n in next
select ac.Concat(new[] {n})));
然而,最初我实现它的方法如下:
var lists = new List<List<int>>
{
new List<int> { 4, 3, 7},
new List<int> { 1, 2, 9},
new List<int> { 5, 8},
};
var agg = lists.Aggregate(
new List<List<int>>() {new List<int> {}},
(acc, next)
=>
(from ac in acc
from n in next
select ac.Add(n)).ToList());
这个具体实现无法编译,出现以下错误:
在查询表达式中,不允许使用类型为“System.Collections.Generic.List”的表达式作为后续 from 子句的源类型,“System.Collections.Generic.List>” 中的调用“SelectMany”类型推断失败。
我对这个错误信息有点困惑。我看不出为什么在那个位置上不允许使用 List
?
Aggregate
的原因。我的问题不是如何执行笛卡尔积,而是关于上面提到的错误。 - Farhad Alizadeh Noori