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?
I’m wondering if there is built-in .NET functionality to change each value in an
Share
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
Selectwould be more functional. Or the existingConvertAllmethod 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.