首页 > 解决方案 > 从具有指定长度的特定索引获取数组值

问题描述

我正在做一些代码挑战,我想通过指定起始索引并从起始索引中仅获取第一个(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;

标签: c#arrayslinq

解决方案


没有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

推荐阅读