12

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?

4 Answers 4

18
List<string> yourList = new List<string>() { "X1", "Y1", "X2", "Y2" };
yourList = yourList.Select(r => string.Concat(r, 'y')).ToList();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for all the answers. I picked this as answer for the Concat, otherwise similar to most of other responses. :-)
7
list = list.Select(s => s + "y").ToList();

Comments

5

An alternative, using ConvertAll:

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

2 Comments

thanks @Paolo, I have tested that this works fine too for my needs. Is there particular reason I should choose the "ConvertAll" approach over the "Select"?
@itsbalur: Not really, infact I used ConvertAll only because there were already several other select-based answers :)
1

You can use Select for that

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.