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...
2 Answers 2
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] + "-";
}
10 Comments
.Select(s => s.Replace("-",""))string is immutable in C# so you can never change it, only create new ones.var copy = list.Select(s => s + "-") .ToList(); list.Clear(); list.AddRange(copy)Try this
List<string> listString = new List<string>() { "1","2","3"};
listString=listString.Select(x => x + "-").ToList();
forloop instead?myStringList[i] += "-";sdirectly as I cycle through, withs.replaceands=s + xthings like that.foreach- You'd have to either use linq to change them or copy the (updated) values to a new collection