c# - 从具有指定长度的特定索引获取数组值
问题描述
我正在做一些代码挑战,我想通过指定起始索引并从起始索引中仅获取第一个(3 个或可以是任何长度)值来从我的数组中获取前 3 个值。
我尝试了这段代码并且它正在工作,但是代码结构太长了,所以我怎样才能使它更短,以便于理解。
int n = 10;
double signature = new double[] { 1, 1, 1 };
double[] ret = new double[n];
double sum = 0;
ret[0] = signature[0];
ret[1] = signature[1];
ret[2] = signature[2];
int x, i;
for (i = 0; i < n - signature.Length; i++)
{
for(x = i; x <= signature.Length + i; x++)
{
sum += ret[x];
}
ret[x - 1] = sum;
sum = 0;
}
return ret;
解决方案
没有Linq解决方案:
private static T[] Extract<T>(T[] source, int fromIndex, int length) {
if (null == source)
throw new ArgumentNullException(nameof(source));
else if (fromIndex < 0)
throw new ArgumentOutOfRangeException(nameof(fromIndex),
"From Index must be non-negative");
else if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length),
"Length must be non-negative");
if (fromIndex >= source.Length || length == 0)
return new T[0];
T[] result = new T[Math.Min(length, source.Length - fromIndex)];
Array.Copy(source, fromIndex, result, 0, result.Length);
return result;
}
然后
double[] signature = new double[] { 0, 1, 2, 3, 4, 5 };
double[] ret = Extract(signature, 3, 2);
Console.Write(string.Join(", ", ret));
结果:
3, 4
推荐阅读
- java - 无法添加子实体 - JPA OneToMany 关系
- c# - OPC-UA“值”和“属性值”有什么区别
- vue.js - 安装 VueJS CLI 时如何修复 npm WARN deprecated 错误
- python - 拆分字符串行代码而不拆分其输出
- asp.net-core - 如何在.net核心中为多个请求运行api
- c++ - 为什么我不能将 rand() 与数组的大小一起使用?
- html - 为什么我的链接样式表中的某些 CSS 格式未应用?
- c# - 有没有办法在 SinglePage 中包含 2 个 Angular 应用程序?
- android - Android:如何断开已连接的蓝牙设备?
- xamarin - 条目未使用可绑定属性清除