合并2列出

2023-09-07 02:52:17 作者:氓

例如我有这两个名单:

List<string> firstName = new List<string>();
List<string> lastName = new List<string>();

我如何可以连接的firstName [0]和lastName [0],名字[1]和lastName [1]等,并把它放在一个新的列表?

How can I concatenate firstName[0] and lastName[0], firstName[1] and lastName[1], etc and put it in a new list?

推荐答案

这听起来像你想的 邮编 从LINQ:

It sounds like you want Zip from LINQ:

var names = firstName.Zip(lastName, (first, last) => first + " " + last)
                     .ToList();

(这不是真正的串联的两个列表。它结合他们的元素,明智的,但这不是真正的同样的事情。)

(This isn't really concatenating the two lists. It's combining them element-wise, but that's not really the same thing.)

编辑:如果您使用的是.NET 3.5,您可以包括邮编办法自己 - 的埃里克利珀的博客文章上有样本code。

If you're using .NET 3.5, you can include the Zip method yourself - Eric Lippert's blog post on it has sample code.

相关推荐