2

I'm trying to cycle through strings in a list with a foreach loop, but I don't know how to change the item that's being referenced - How can I change s in the list... e.g. below I want to add "-" to the end of every string, s in myStringList

foreach(string s in myStringList)
{
    s = s + "-"; 
}

I can't do things to s because it's a "foreach iteration variable" - so can I not change it as I cycle through?

Do I have to use an int to count through?

I'm sure there's a simpler way...

jamheadart
  • 5,047
  • 4
  • 32
  • 63

2 Answers2

15

You can do this with Linq quite easily:

var newStringList = myStringList
    .Select(s => s + "-")
    .ToList();

If you really want to modify the existing list, you can use a classic for loop, for example:

for (var i = 0; i < myStringList.Count; i++)
{
    myStringList[i] = myStringList[i] + "-";
}
DavidG
  • 113,891
  • 12
  • 217
  • 223
  • I take it this'd work with string functions too like `.Select(s => s.Replace("-",""))` – jamheadart Jun 15 '18 at 12:43
  • 2
    Yes, you're creating new strings and assigning the result to a completely new list. Remember that `string` is immutable in C# so you can never change it, only create new ones. – DavidG Jun 15 '18 at 12:44
  • Funny when you say a keyword and something clicks. Immutable! I'm with you. – jamheadart Jun 15 '18 at 12:46
  • A potential issue with the LINQ solution, since a completely new list has been created, is that any references to the old list won't see the change. _This may not be an issue if this is the only reference to the list._ – mjwills Jun 15 '18 at 12:47
  • 1
    @mjwills If you really (unlikely) want to cover this case, you can `var copy = list.Select(s => s + "-") .ToList(); list.Clear(); list.AddRange(copy)` – vc 74 Jun 15 '18 at 12:52
  • Actually I'm just wondering - I create the list by splitting a large string - is there a way to append or replace things immediately to the split list?! – jamheadart Jun 15 '18 at 12:55
  • @jamheadart Something like `stringVariable.Split("...").Select(s => s + "-")...` – DavidG Jun 15 '18 at 12:57
  • Just adding, remember also that `.ToList()` is not absolutely required with the Linq example, it is just a matter of if one desires deferred execution or not and the possible implications. – blins Jun 15 '18 at 16:30
  • @vc74 Or, easier, `myStringList = myStringList.Select(s => s + "-").ToList();` Technically different, but does the exact same thing faster in practice, because you are making 3 lists instead of 2. – PRMan Nov 23 '21 at 17:13
  • @PRMan No, it won't be faster at all. There are still the same number of lists being created. Just because one of them doesn't have a named variable doesn't mean it doesn't exist. – DavidG Nov 23 '21 at 17:30
-2

Try this

List<string> listString = new List<string>() { "1","2","3"};
listString=listString.Select(x => x + "-").ToList();
GaneshJ
  • 35
  • 3