Search code examples
c#linqarraysdelegatesprojection

C#: Altering values for every item in an array


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?


Solution

  • 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:

    public static void ConvertInPlace<T>(this IList<T> source, Func<T, T> projection)
    {
        for (int i = 0; i < source.Count; i++)
        {
            source[i] = projection(source[i]);
        }
    }
    

    Use:

    int[] values = { 1, 2, 3 };
    values.ConvertInPlace(x => x * x);
    

    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 existing ConvertAll method from .NET 2:

    int[] values = { 1, 2, 3 };
    values = Array.ConvertAll(values, x => x * x);
    

    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.