更新时间:2023-11-28 15:41:22
这并不是说我知道(更换每一个元素,而不是转换到一个新的数组或序列),但它是非常容易写:
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]);
}
}
使用:
int[] values = { 1, 2, 3 };
values.ConvertInPlace(x => x * x);
当然,如果你真的不需要的改变现有的阵列,其他的答案使用选择
将更多的功能发布。或现有的 ConvertAll
从.NET 2的方法:
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.