简体   繁体   English

如何使用LINQ组合2个列表?

[英]How to combine 2 lists using LINQ?

Env.: .NET4 C# 环境:.NET4 C#

Hi All, 大家好,

I want to combine these 2 lists : { "A", "B", "C", "D" } and { "1", "2", "3" } 我想结合这两个列表: { "A", "B", "C", "D" }{ "1", "2", "3" }

into this one: 进入这一个:

{ "A1", "A2", "A3", "B1", "B2", "B3", "C1", "C2", "C3", "D1", "D2", "D3" }

Obviously, i could use nested loops. 显然,我可以使用嵌套循环。 But I wonder if LINQ can help. 但我想知道LINQ是否可以提供帮助。 As far as I understand, Zip() is not my friend in this case, right? 据我所知,Zip()在这种情况下不是我的朋友,对吧?

TIA, TIA,

当您想要形成两个列表的笛卡尔积时,请使用SelectMany:

aList.SelectMany(a => bList.Select(b => a + b))

Essentially, you want to generate a cartesian product and then concatenate the elements of each 2-tuple. 基本上,您希望生成笛卡尔积,然后连接每个2元组的元素。 This is easiest to do in query-syntax: 这在查询语法中最容易做到:

var cartesianConcat = from a in seq1
                      from b in seq2
                      select a + b;

SelectMany is definitely the right approach, whether using multiple "from" clauses or with a direct call, but here's an alternative to Hightechrider's use of it: SelectMany绝对是正确的方法,无论是使用多个“from”子句还是直接调用,但这里是Hightechrider使用它的替代方法:

var result = aList.SelectMany(a => bList, (a, b) => a + b);

I personally find this easier to understand as it's closer to the "multiple from" version: for each "a" in "aList", we produce a new sequence - in this case it's always "bList". 我个人觉得这更容易理解,因为它更接近“倍数”版本:对于“aList”中的每个“a”,我们产生一个新序列 - 在这种情况下,它总是“bList”。 For each (a, b) pair produced by the Cartesian join, we project to a result which is just the concatenation of the two. 对于由笛卡尔连接产生的每个(a,b)对,我们投射到的结果只是两者的串联。

Just to be clear: both approaches will work. 需要明确的是:两种方法都有效。 I just prefer this one :) 我只是喜欢这一个:)

As to whether this is clearer than the query expression syntax... I'm not sure. 至于这是否比查询表达式语法更清楚......我不确定。 I usually use method calls when it's just a case of using a single operator, but for Join , GroupJoin , SelectMany and GroupBy , query expressions do simplify things. 通常使用方法调用,只是使用单个运算符的情况,但对于JoinGroupJoinSelectManyGroupBy ,查询表达式确实简化了事情。 Try both and see which you find more readable :) 尝试两者,看看发现哪些更具可读性:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM