说我有两个列表:
VAR的List1 =新INT [] {1,2,3};
VAR list2中=新的String [] {A,B,C};
是否可以写一个LINQ语句,将产生以下列表:
VAR的结果=新的[] {
新{I = 1,S =一个},
新{I = 1,S =B},
新{I = 1,S =C},
新{设为i = 2,S =一个},
新{设为i = 2,S =B},
新{I = 2,S =C},
新{I = 3,S =一个},
新{I = 3,S =B},
新{I = 3,S =C}
};
编辑:我忘了提我不希望它在查询语法。总之,根据我得到了以下preetsangha的回答是:
VAR的结果= list1.SelectMany(I => list2.Select(S =>新建{I = I,S = S}));
解决方案
preetsangha的答案是完全正确的,但如果你不想查询EX pression那么它的:
VAR的结果= list1.SelectMany(L1 => list2中,(L1,L2)=>新建{I = L1,S = 12});
(这就是编译器编译查询EX pression到 - 他们是相同的)
Say I have two lists:
var list1 = new int[] {1, 2, 3};
var list2 = new string[] {"a", "b", "c"};
Is it possible to write a LINQ statement that will generate the following list:
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"}
};
?
Edit: I forgot to mention I didn't want it in query syntax. Anyway, based on preetsangha's answer I've got the following:
var result = list1.SelectMany(i => list2.Select(s => new {i = i, s = s}));
解决方案
preetsangha's answer is entirely correct, but if you don't want a query expression then it's:
var result = list1.SelectMany(l1 => list2, (l1, l2) => new { i = l1, s = l2} );
(That's what the compiler compiles the query expression into - they're identical.)