C#: Altering values for every item in an array(C#:更改数组中每个项目的值)
问题描述
我想知道是否有内置的 .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#:更改数组中每个项目的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C#:更改数组中每个项目的值
基础教程推荐
- c# Math.Sqrt 实现 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- SSE 浮点算术是否可重现? 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01