Linq to return ALL pairs of elements from two lists?

前端 未结 7 1504
日久生厌
日久生厌 2021-01-17 10:56

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,         


        
相关标签:
7条回答
  • 2021-01-17 11:24

    You want

    l1.Join(l2, a => 1, b => 1, (a, b) => new [] { a, b });
    
    0 讨论(0)
  • 2021-01-17 11:35

    Here you go;

    var rez =  from first in l1 
               from second in l2 
               select new[] { first, second };
    
    0 讨论(0)
  • 2021-01-17 11:38

    Great article by Eric Lippert - see links in other answers. What's even better, this was the first try I did before looking at the answers on this page :)

    In short:

    var rez = 
        from e1 in l1
        from e2 in l2 
        select new {e1, e2};
    
    0 讨论(0)
  • 2021-01-17 11:40

    something like this will do what you are looking for.

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

    with this answer your tuples {x,y} are an anonymous type.

    0 讨论(0)
  • 2021-01-17 11:46

    Eric Lippert's already done it for you!

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

    you probably just want to the linq fluent syntax of SelectMany

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

    or Eric's blog post version

    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();

    0 讨论(0)
  • 2021-01-17 11:46
    var result = from a in l1
                 from b in l2
                 select new[] { a, b }
    
    0 讨论(0)
提交回复
热议问题