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#:更改数组中每个项目的值
基础教程推荐
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 如果条件可以为空 2022-01-01
- 将数据集转换为列表 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
