C # using Array.ForEach Action Predicate with an array of type value or string

I correctly understood that the following fragment does not work (the elements of the array are not changed), because the array has an integer, which is a value type.

class Program
{
    public static void Main()
    {
        int[] ints = new int[] { 1,2 };

        Array.ForEach(ints, new Action<int>(AddTen));

        // ints is not modified
    }
    static void AddTen(int i)
    {
        i+=10;
    }
}

The same applies if the example used a string array, presumably because the string is immutable.

I have a question: -

Is there any way around this? I cannot change the signature of the callback method - for example, by adding the ref keyword, and I do not want the value type to be associated with the class - which would work ...

(Of course, I could just write an old-fashioned foreach loop to do this!)

+3
source share
4 answers

- . ConvertAll, /:

    int[] ints = new int[] { 1,2 };

    int[] newArr = Array.ConvertAll<int,int>(ints, AddTen);

:

static int AddTen(int i)
{
    return i+10;
}

:

int[] newArr = Array.ConvertAll<int,int>(ints,
    delegate (int i) { return i+ 10;});

# 3.0 :

int[] newArr = Array.ConvertAll(ints, i=>i+10);

... a for loop:

for(int i = 0 ; i < arr.Length ; i++) {
    arr[i] = AddTen(arr[i]); // or more directly...
}

, . , .

+9

Array.ForEach() . , LINQ,

ints = ints.Select(x => x +10 ).ToArray();
+4

foreach - , , , . AddTen , .

0

First, it’s usually dangerous to modify the collection you are in foreach. Most collections support an internal “version tag” to track changes, so the enumerator will throw an exception when it tries to iterate over the modified collection.

As for your question, you cannot do this with type values ​​and Array.ForEach. Use foreachor Convertto do what you want.

0
source

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


All Articles