C#: Altering values for every item in an array

前端 未结 6 1295
醉梦人生
醉梦人生 2020-12-30 01:54

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,

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-30 02:45

    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(this IList source, Func 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.

提交回复
热议问题