问题描述
我想知道是否有内置的 .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#:更改数组中每个项目的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)