C# 你能用 LINQ 组合多个列表吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/289307/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 21:48:52  来源:igfitidea点击:

Can you combine multiple lists with LINQ?

c#.netlinq

提问by Cameron MacFarland

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:

是否可以编写将生成以下列表的 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"}
};

?

?

Edit: I forgot to mention I didn't want it in query syntax. Anyway, based on preetsangha's answer I've got the following:

编辑:我忘了提到我不想在查询语法中使用它。无论如何,根据 preetsangha 的回答,我得到了以下信息:

var result = list1.SelectMany(i =>  list2.Select(s => new {i = i, s = s}));

采纳答案by Jon Skeet

preetsangha's answer is entirely correct, but if you don't want a query expression then it's:

preetsangha 的答案是完全正确的,但如果您不想要查询表达式,那么它是:

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

(这就是编译器将查询表达式编译成的内容 - 它们是相同的。)

回答by Preet Sangha

var result = from l1 in list1
             from l2 in list2       
             select new { i = l1, s = l2};