Merging 2 Lists
Asked Answered
F

2

6

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?

Ferrotype answered 10/9, 2013 at 5:51 Comment(0)
F
7

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.

Featly answered 10/9, 2013 at 5:52 Comment(9)
What if I want to put the result to a new list? Is it possible?Ferrotype
@ChrisN.P.: That does put the result in a new list - that's why there's a ToList call.Featly
I tried this and I got an error: "Error 1 'System.Collections.Generic.List<string>' does not contain a definition for 'Zip' and no extension method 'Zip' accepting a first argument of type 'System.Collections.Generic.List<string>' could be found (are you missing a using directive or an assembly reference?) D:\ChrisN.P\My Files\My Files\C#\Projects\ConsoleApplication1\ConsoleApplication1\Program.cs 24 30 ConsoleApplication1 "Ferrotype
I'm using System.Linq.Ferrotype
@ChrisN.P.: It should be fine if you're using .NET 4 or higher. Which version of .NET are you using?Featly
@ChrisN.P.: That would explain it - see my edit. (In the future, if you're using a pretty old version of a platform, it's usually worth saying so in the question.)Featly
Alright thanks! (Though I'm not sure if .net 3.5 is really that old) :)Ferrotype
@ChrisN.P.: Well its successor came out over three years ago (April 2010) which makes it pretty old in my view...Featly
You have a point there. Well, this works for me now thank you Jon. Cheers! ;)Ferrotype
P
0

You can Use Linq Concat and ToList methods

var lists = firstname.Concat(lastname).ToList();

Peony answered 10/9, 2013 at 7:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.