Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging 2 Lists

For example I have these two lists:

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

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

like image 947
Chris N.P. Avatar asked Sep 10 '13 05:09

Chris N.P.


1 Answers

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

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

like image 123
Jon Skeet Avatar answered Oct 27 '22 14:10

Jon Skeet