Linq从两个列表中返回所有元素对?
给定列表l1 = {1, 2}
和l2 = {4, 5, 6 }
我想获得一个包含元素的新列表:
rez = { {1, 4}, {1, 5}, {1, 6}, {2, 4}, {2, 5}, {2, 6} }
建议?
对的,这是可能的。 Eric Lippert写了一篇关于这个主题的非常好的文章:
使用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> CartesianProduct(this IEnumerable> sequences) { IEnumerable> emptyProduct = new[] { Enumerable.Empty () }; 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}
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> CartesianProduct(this IEnumerable> sequences) { // base case: IEnumerable> result = new[] { Enumerable.Empty () }; 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();
var result = from a in l1 from b in l2 select new[] { a, b }
干得好;
var rez = from first in l1 from second in l2 select new[] { first, second };
这样的事情会做你想要的。
var l1 = new List{1,2}; var l2 = new List {4,5,6}; var p = from n in l1 from m in l2 select new { Fst = n, Scd = m };
有了这个答案你的元组{x,y}是一个匿名类型。
Eric Lippert撰写的精彩文章 – 请参阅其他答案中的链接。 甚至更好,这是我在查看此页面上的答案之前的第一次尝试:)
简而言之:
var rez = from e1 in l1 from e2 in l2 select new {e1, e2};
你要
l1.Join(l2, a => 1, b => 1, (a, b) => new [] { a, b });