开发者

c# Array.ForEach alternative that replaces elements

开发者 https://www.devze.com 2023-02-19 21:16 出处:网络
Is there a standard function I can use that iterates over an array similarly to ForEach, applying a function to each element and replacing it in the array with the result?

Is there a standard function I can use that iterates over an array similarly to ForEach, applying a function to each element and replacing it in the array with the result?

Something like the following, but where开发者_Python百科 dimension powers afterwards contains the results of IntPow(2, i) on each element.

dimensionPowers = Enumerable.Range(0, dimensions + 1).ToArray();
Array.ForEach(dimensionPowers,
    (i) => IntPow(2, i));

(I know I can iterate over the array with a for loop - I'm just wondering if there's a more concise alternative).


The MSDN docs says that the designers deliberately did not put in a "ForEach" with an Array due to the fact that: 1) it is trivial to write, 2) exactly your problem -- people will get confused whether the original array is modified or not.

Most of the ForEach types of array iterator implementation (you actually need a "map" function) returns a new instance of an array. For example, you can use LINQ:

newArray = dimensionPowers.Select(i => IntPow(2,i)).ToArray();

or better:

dimensionPowers = Enumerable.Range(0, dimensions + 1).Select(i => IntPow(2,i)).ToArray();

However, if you want to modify the original array in-place, there is the good old for-loop:

for (int i=0; i < dimensionPowers.Length; i++) { dimensionPowers[i] = IntPow(2,i); }

The designers for .NET forces you to use these different methods just so that you'll know when an array is modified.

If you want to implement your in-place modification, you can create an extension method:

static void ForEachModifyInPlace<T> (this Array<T> array, Func<T,T> map_action) {
    for (int i=0; i < array.Length; i++) { array[i] = map_action(array[i]); }
}


I don't think you can do it much more concisely (using existing methods).

You could collapse the two steps in one:

dimensionPowers = Enumerable.Range(0, dimensions + 1).Select(i => IntPow(2, i)).ToArray();
0

精彩评论

暂无评论...
验证码 换一张
取 消