C#:数组中的值变更为每个项目 [英] C#: Altering values for every item in an array
问题描述
如果有内置的.NET功能改变的基础上提供的委托的结果数组中的每个值我不知道。举例来说,如果我有一个数组 {1,2,3}
键,返回每个值的平方代表,我希望能够运行一个方法取数组和委托,并返回 {1,4,9}
。请问像这样的东西已经存在?
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?
推荐答案
这并不是说我知道(更换每一个元素,而不是转换到一个新的数组或序列),但它是非常容易写:
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.
这篇关于C#:数组中的值变更为每个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!