接受的答案似乎是正确的,但在 C# 中做笛卡尔积是一种非常奇怪的方式。如果您有给定数量的序列,您可以像这样惯用地采用他们的笛卡尔积:
var aList = new[] { "a1", "a2", "a3" };
var bList = new[] { "b1", "b2", "b3" };
var cList = new[] { "c1", "c2", "c3" };
var product = from a in aList
from b in bList
from c in cList
select new[] { a, b, c };
foreach (var p in product)
Console.WriteLine(string.Join(",", p));
如果您有任意多个序列需要获取他们的笛卡尔积,那么您可以这样做:
static class Extensions
{
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}));
}
}
接着:
var aList = new[] { "a1", "a2", "a3" };
var bList = new[] { "b1", "b2", "b3" };
var cList = new[] { "c1", "c2", "c3" };
var lists = new[] { aList, bList, cList };
var product = lists.CartesianProduct();
foreach (var p in product)
Console.WriteLine(string.Join(",", p));
看
http://ericlippert.com/2010/06/28/computing-a-cartesian-product-with-linq/
和我的回答
生成所有可能的组合
有关此问题的更多讨论。