Modify an array using Array.Foreach and lambda expression

I am trying to change the values ​​of an array, but it does not change:

string buzones = File.ReadAllText("c:\\Buzones"); string[] buzoneslist = buzones.Split(','); Array.ForEach(buzoneslist, x => { x = x.Replace(",", ""); }); 

I like that I do string.Replace without setting the resulting value for the variable:

s.replace(",", ""); instead of s=s.replace(",", "");

Is it possible to execute inside lambda expressions ?.

+4
source share
1 answer

No, you cannot modify the array while you enumerate it using ForEach , and the strings are immutable, so there is no function that will modify the instance in place.

You can do the following:

 for (int i=0; i<buzoneslist.Length; i++) buzoneslist[i] = buzoneslist[i].Replace(",", ""); 

Or:

 buzoneslist = buzoneslist.Select(t => t.Replace(",", "")).ToArray(); 

I suppose if you really wanted to use lambda, you could write an extension method:

 public static class Extensions { public static void ChangeEach<T>(this T[] array, Func<T,T> mutator) { for (int i=0; i<array.Length; i++) { array[i] = mutator(array[i]); } } } 

And then:

 buzoneslist.ChangeEach(t => t.Replace(",", "")); 
+14
source

Source: https://habr.com/ru/post/1485557/


All Articles