Toubi
Toubi

Reputation: 2509

Concatenating strings in two lists to create a third list

I have two lists of items, can you please guide me how I can concatenate values of both and add concatenated value into third list as a value.

For example if List<string> From has A,B,C and List<string> To has 1,2,3 then List<string> All should have A1,B2,C3. I'd preferably like to use a lambda expression.

Upvotes: 2

Views: 971

Answers (3)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

That's not concatenation - that's matching two sequences pairwise. You do it with LINQ's Zip method:

Zip applies a specified function to the corresponding elements of two sequences, producing a sequence of the results.

var res = from.Zip(to, (a,b) => a + b).ToList();

Upvotes: 4

p.s.w.g
p.s.w.g

Reputation: 149020

Use Linq's Zip extension method:

using System.Linq;
...

var list1 = new List<string> { "A", "B", "C" };
var list2 = new List<string> { "1", "2", "3" };
var list3 = list1.Zip(list2, (x, y) => x + y).ToList(); // { "A1", "B2", "C3" }

Upvotes: 4

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

If item's count are equal in both lists then you can do:

var list3 = list1.Select((item, index) => item + list2[index]).ToList();

Upvotes: 1

Related Questions