2

I have this List of strings:

List<string> result = new List<string>();      

result.Add("dummy1");
result.Add("dummy2");
result.Add("dummy3");
result.Add("dummy4");

I want to change items in result variable to add some string posfix:

result[0]("dummy1-aaa");
result[1]("dummy2-aaa");
result[2]("dummy3-aaa");
result[3]("dummy4-aaa");

I know that I can use for loop iterate on result variable and put new string to the item.

But my question is how can I change it using LINQ to object?

5
  • Do you need to modify the existing list, or are you happy to create a new list? (LINQ is query-oriented; it doesn't provide modification capabilities in itself.) Commented Jun 18, 2018 at 12:30
  • strings are immutable, you'd be replacing an element with a new string really. Commented Jun 18, 2018 at 12:31
  • Try this. result.Select(r => string.Concat(r, "-aaa")).ToList(); Commented Jun 18, 2018 at 12:33
  • @DaisyShipton, I want to add only new string inside result. Commented Jun 18, 2018 at 12:36
  • 2
    @Michael: It's not clear to me that that answers the question. You've now got two answers, neither of which modify the existing list - they both create new lists. If you have another variable with a reference to the existing list, that won't observe any changes with those "create a new list" options. Commented Jun 18, 2018 at 12:40

2 Answers 2

15

You can write something like this:

result = result.Select(s => $"{s}-aaa").ToList();

or below C#6

result = result.Select(s => string.Format("{0}-aaa", s)).ToList();
Sign up to request clarification or add additional context in comments.

3 Comments

what is meaning of $ ?
$ - is string interpolation character. String interpolation is turned into string.Format() at compile-time.
1

You can try, like:

var newList = result.Select(r=>r+"-aaa").ToList();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.