Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify array with Array.Foreach and lambda expression

I'm trying to modify the values of the array but it doesn't get modified:

string buzones = File.ReadAllText("c:\\Buzones");
string[] buzoneslist = buzones.Split(',');

Array.ForEach(buzoneslist, x =>
{
    x = x.Replace(",", "");
});

It's like I'm doing a string.Replace without setting the resultant value to the variable:

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

Is it possible to accomplish inside a lambda expression?.

like image 575
Carlos Landeras Avatar asked Jun 11 '13 06:06

Carlos Landeras


People also ask

Does forEach modify array?

forEach() does not mutate the array on which it is called. (However, callback may do so).

Can you use forEach on Array C#?

ForEach() is a declarative syntax form—this simplifies certain code patterns. Usually the Array. ForEach method is mostly used on arrays of objects.


1 Answers

No, you can't modify an array while you're enumerating it with ForEach, and strings are immutable so there's no function that will modify the instance in-place.

You could do either:

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 a 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(",", ""));
like image 184
Blorgbeard Avatar answered Nov 15 '22 21:11

Blorgbeard