I'm wondering if there is built-in .NET functionality to change each value in an array based on the result of a provided delegate. For example, if I had an array {1,2,3}
and a delegate that returns the square of each value, I would like to be able to run a method that takes the array and delegate, and returns {1,4,9}
. Does anything like this exist already?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
LINQ provides support for projections using the Select extension method:
You can also use the slightly less fluent Array.ConvertAll method:
Jagged arrays can be processed by nesting the projections:
Multidimensional arrays are a little more complex. I've written the following extension method which projects every element in a multidimensional array no matter what its rank.
The above method can be tested with an array of rank 3 as follows:
you can use linq to accomplish this in shorthand but be careful remember that a foreach occurs underneath anyway.
Here is another solution for M x N arrays, where M and N are not known at compile time.
Using System.Linq you could do something like:
Not that I'm aware of (replacing each element rather than converting to a new array or sequence), but it's incredibly easy to write:
Use:
Of course if you don't really need to change the existing array, the other answers posted using
Select
would be more functional. Or the existingConvertAll
method from .NET 2:This is all assuming a single-dimensional array. If you want to include rectangular arrays, it gets trickier, particularly if you want to avoid boxing.
LINQ queries could easily solve this for you - make sure you're referencing System.Core.dll and have a
statement. For example, if you had your array in a variable named numberArray, the following code would give you exactly what you're looking for:
The final "ToArray" call is only needed if you actually need an array, and not an IEnumerable<int>.