Linq从两个列表返回所有元素对?

Cri*_*scu 16 .net c# linq

给定列表l1 = {1, 2},l2 = {4, 5, 6 }我想获得一个包含元素的新列表:

rez = { {1, 4}, {1, 5}, {1, 6}, {2, 4}, {2, 5}, {2, 6} }
Run Code Online (Sandbox Code Playgroud)

建议?

Rom*_*ier 30

对的,这是可能的.Eric Lippert写了一篇关于这个主题的非常好的文章:

使用LINQ计算笛卡尔积

如果你只有2个列表,那么你可以直接使用多个from这样的:

from a in s1 
from b in s2 
select new [] { a, b};
Run Code Online (Sandbox Code Playgroud)

甚至:

s1.SelectMany(a => s2.Select(b => new [] { a, b }));
Run Code Online (Sandbox Code Playgroud)

但Eric Lippert在前一篇文章中给出的解决方案允许您计算几个序列的笛卡尔积.使用以下扩展方法:

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 }));
}
Run Code Online (Sandbox Code Playgroud)

你可以写:

var l1 = new[] {1, 2};
var l2 = new[] {4, 5, 6};
var l3 = new[] {7, 3};

foreach (var result in new []{l1,l2,l3}.CartesianProduct())
{
    Console.WriteLine("{"+string.Join(",",result)+"}");
}
Run Code Online (Sandbox Code Playgroud)

并获得:

{1,4,7}
{1,4,3}
{1,5,7}
{1,5,3}
{1,6,7}
{1,6,3}
{2,4,7}
{2,4,3}
{2,5,7}
{2,5,3}
{2,6,7}
{2,6,3}
Run Code Online (Sandbox Code Playgroud)