说我有两个清单:
var list1 = new int[] {1, 2, 3};
var list2 = new string[] {"a", "b", "c"};
是否可以编写一个LINQ语句来生成以下列表:
var result = new []{
new {i = 1, s = "a"},
new {i = 1, s = "b"},
new {i = 1, s = "c"},
new {i = 2, s = "a"},
new {i = 2, s = "b"},
new {i = 2, s = "c"},
new {i = 3, s = "a"},
new {i = 3, s = "b"},
new {i = 3, s = "c"}
};
编辑:我忘了提到我在查询语法中不想要它。无论如何,根据preetsangha的回答,我得到了以下内容:
var result = list1.SelectMany(i => list2.Select(s => new {i = i, s = s}));
答案 0 :(得分:43)
var result = from l1 in list1
from l2 in list2
select new { i = l1, s = l2};
答案 1 :(得分:21)
preetsangha的回答是完全正确的,但是如果你不想要一个查询表达式那么它就是:
var result = list1.SelectMany(l1 => list2, (l1, l2) => new { i = l1, s = l2} );
(这就是编译器将查询表达式编译成的内容 - 它们是相同的。)