问题描述
我想知道是否有内置的 .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);
当然,如果您真的 需要 更改现有数组,则使用 Select
发布的其他答案会更实用.或 .NET 2 中现有的 ConvertAll
方法:
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#:更改数组中每个项目的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!