Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing element value in List<T>.ForEach ForEach method

Tags:

c#

linq

c#-3.0

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?

like image 423
Jon Avatar asked Jul 21 '09 16:07

Jon


People also ask

Can we modify List in foreach?

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.

Can you use foreach on a List?

forEach statement is a C# generic statement which you can use to iterate over elements of a List.


1 Answers

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.

like image 101
jason Avatar answered Oct 06 '22 04:10

jason