itsbalur
itsbalur

Reputation: 1002

Concatenate a constant string to each item in a List<string> using LINQ

I am using C# and .Net 4.0.

I have a List<string> with some values, say x1, x2, x3. To each of the value in the List<string>, I need to concatenate a constant value, say "y" and get back the List<string> as x1y, x2y and x3y.

Is there a Linq way to do this?

Upvotes: 12

Views: 14007

Answers (4)

Paolo Tedesco
Paolo Tedesco

Reputation: 57202

An alternative, using ConvertAll:

List<string> l = new List<string>(new [] {"x1", "x2", "x3"} );
List<string> l2 = l.ConvertAll(x => x + "y");

Upvotes: 5

Asif Mushtaq
Asif Mushtaq

Reputation: 13150

You can use Select for that

var list = new List<string>(){ "x1", "x2" };

list = list.Select(s =>  s + "y").ToList();

Upvotes: 1

Habib
Habib

Reputation: 223267

List<string> yourList = new List<string>() { "X1", "Y1", "X2", "Y2" };
yourList = yourList.Select(r => string.Concat(r, 'y')).ToList();

Upvotes: 18

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236228

list = list.Select(s => s + "y").ToList();

Upvotes: 7

Related Questions