I have the following code:
newsplit.ToList().ForEach(x => x = "WW");
I would expect that all elements in the list are now "WW" but they are still the original value. How come? What do I have to do different?
Modify a C# collection with foreach by using a second collection. Since we cannot change a collection directly with foreach , an alternative is to use a second collection. To that second collection we then add new elements. This way we can still benefit from the simplicity that foreach offers.
forEach statement is a C# generic statement which you can use to iterate over elements of a List.
Assuming that newsplit
is an IEnumerable<string>
, you want:
newsplit = newsplit.Select(x => "WW");
The code that you currently have is equivalent to the following:
foreach(string x in newsplit.ToList()) { AssignmentAction(x); } ... public static void AssignmentAction(string x) { x = "WW"; }
This method won't modify x
because of the pass-by-value semantics of C# and the immutability of strings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With