【发布时间】:2014-09-04 15:22:46
【问题描述】:
我需要创建一组列表的笛卡尔积。例如我有:
{ {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?
【问题讨论】:
-
试试 Eric Lippert 的博客文章:blogs.msdn.com/b/ericlippert/archive/2010/06/28/…
-
你知道有多少个列表还是N个列表?
-
@DavidG 感谢 linq。我已经读过那篇文章,我想这就是我记得使用
Aggregate的方式。我的问题不是关于如何做笛卡尔积,而是关于上面提到的错误。 -
@terrybozzio 这是任意数量的项目(N 项目)。
标签: c# linq generics cartesian-product