1

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?

Michael
  • 13,950
  • 57
  • 145
  • 288
  • 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.) – Jon Skeet Jun 18 '18 at 12:30
  • strings are immutable, you'd be replacing an element with a new string really. – Josh Adams Jun 18 '18 at 12:31
  • Try this. `result.Select(r => string.Concat(r, "-aaa")).ToList();` – Rishi Malviya Jun 18 '18 at 12:33
  • @DaisyShipton, I want to add only new string inside result. – Michael Jun 18 '18 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. – Jon Skeet Jun 18 '18 at 12:40

2 Answers2

14

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();
SᴇM
  • 7,024
  • 3
  • 24
  • 41
  • what is meaning of $ ? – Michael Jun 18 '18 at 12:51
  • It defines an interpolated string. See https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated – apomene Jun 18 '18 at 12:52
  • `$` - is [string interpolation](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated) character. String interpolation is turned into [string.Format()](https://msdn.microsoft.com/en-us/library/system.string.format%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396) at compile-time. – SᴇM Jun 18 '18 at 12:53
1

You can try, like:

var newList = result.Select(r=>r+"-aaa").ToList();
apomene
  • 14,282
  • 9
  • 46
  • 72