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

时间:2010-08-26 14:09:14

标签: c# .net linq

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

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

建议?

7 个答案:

答案 0 :(得分:30)

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

Computing a Cartesian Product with LINQ

如果您只有2个列表,那么您可以直接使用多个from,如下所示:

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

甚至:

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

但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 }));
}

你可以写:

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}

答案 1 :(得分:4)

Eric Lippert已经为你完成了它!

http://blogs.msdn.com/b/ericlippert/archive/2010/06/28/computing-a-cartesian-product-with-linq.aspx

你可能只想要SelectMany

的linq流利语法
var s1 = new[] {a, b}; 
var s2 = new[] {x, y, z}; 


var product = 
from first in s1 
from second in s2 
select new[] { first, second };

product.SelectMany(o=>o);

或Eric的博客文章

static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) 
{ 
  // base case: 
  IEnumerable<IEnumerable<T>> result = new[] { Enumerable.Empty<T>() }; 
  foreach(var sequence in sequences) 
  { 
    var s = sequence; // don't close over the loop variable 
    // recursive case: use SelectMany to build the new product out of the     old one 
    result = 
      from seq in result 
      from item in s 
      select seq.Concat(new[] {item}); 
  } 
  return result; 
}

product.CartesianProduct();

答案 2 :(得分:3)

var result = from a in l1
             from b in l2
             select new[] { a, b }

答案 3 :(得分:2)

你走了;

var rez =  from first in l1 
           from second in l2 
           select new[] { first, second };

答案 4 :(得分:1)

Eric Lippert的精彩文章 - 请参阅其他答案中的链接。 甚至更好,这是我在查看本页答案之前的第一次尝试:)

简而言之:

var rez = 
    from e1 in l1
    from e2 in l2 
    select new {e1, e2};

答案 5 :(得分:1)

这样的事情会做你想要的。

var l1 = new List<int>{1,2};
var l2 = new List<int>{4,5,6};

var p = from n in l1
        from m in l2
        select new { Fst = n, Scd = m };

使用此答案,您的元组{x,y}是匿名类型。

答案 6 :(得分:-3)

你想要

l1.Join(l2, a => 1, b => 1, (a, b) => new [] { a, b });