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...

9
  • 4
    Have you considered using a for loop instead? myStringList[i] += "-"; Commented Jun 15, 2018 at 12:41
  • Alternative way would be using LINQ expressions Commented Jun 15, 2018 at 12:41
  • I have but I honestly thought there'd be a really simple "ref" keyword to chuck in and alter the s directly as I cycle through, with s.replace and s=s + x things like that. Commented Jun 15, 2018 at 12:42
  • You can't change values while iterating through them in a foreach - You'd have to either use linq to change them or copy the (updated) values to a new collection Commented Jun 15, 2018 at 12:43
  • 1
    Possible duplicate of c# string.replace in foreach loop Commented Jun 15, 2018 at 12:46

2 Answers 2

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] + "-";
}
Sign up to request clarification or add additional context in comments.

10 Comments

I take it this'd work with string functions too like .Select(s => s.Replace("-",""))
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.
Funny when you say a keyword and something clicks. Immutable! I'm with you.
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 If you really (unlikely) want to cover this case, you can var copy = list.Select(s => s + "-") .ToList(); list.Clear(); list.AddRange(copy)
|
-2

Try this

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

1 Comment

I posted basically the same solution 10 minutes ago, how is yours any different?

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.