LINQ到来自两个列表返回所有元素对?元素、两个、列表、LINQ

2023-09-04 07:28:46 作者:谈笑风月间

鉴于名单 L1 = {1,2} L2 = {4,5,6} 我要以获得一个新的列表具有元素:

Given lists l1 = {1, 2} and l2 = {4, 5, 6 } I want to get a new list that has elements:

rez = { {1, 4}, {1, 5}, {1, 6}, {2, 4}, {2, 5}, {2, 6} }

建议?

推荐答案

是的,它是可能的。埃里克利珀写了关于这个主题非常好文章:

Yes it is possible. Eric Lippert wrote a very good article on this topic:

计算一个乘积LINQ

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

If you only have 2 lists, then you could directly use multiple from like this:

from a in s1 
from b in s2 
select new [] { a, b};

甚至是:

s1.SelectMany(a => s2.Select(b => new [] { a, b }));

但是,埃里克利珀在previous文章中给出的解决方案,可以计算几个序列的笛卡尔积。用下面的扩展方法:

But the solution given by Eric Lippert in the previous article allows you to compute the cartesian product of several sequences. With the following extension method:

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 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)+"}");
}

和获得:

{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}