【问题标题】:Return an array of ints containing the number of elements of each inner array c#返回一个包含每个内部数组元素数量的整数数组c#
【发布时间】:2020-10-27 03:26:32
【问题描述】:

我想编写一个函数,给定输入中的整数数组,输出中返回整数数组,其中包含每个内部数组的元素数。

这是我当前的实现:

public static int[] countEach(int[][] a) {
    int[] count = new int[3];
    for(int i = 0; i < a.Length; i++){
      count[i] = a[i].Length;
    }
    return count;
}

public static void Main(string[] args){
  int[][] a = new int[][]{
    new int[] {1, 2, 3},
    new int[] {1, 2, 3, 4, 5},
    new int[] {1}
  };
  int[] result = countEach(a);
}

它可以工作,但是我不想事先定义一个固定长度为 3。那么我该如何重写它以便它可以接受任何输入数组呢?我想不出,有没有更好的方法来编码?这样我可以更好地掌握c#的编程概念。谢谢

【问题讨论】:

    标签: c# arrays loops for-loop element


    【解决方案1】:

    您可以使用 Linq,通过选择嵌套数组的长度并调用 .ToArray()IEnumerable 转换为 array

    int[] result = a.Select(x => x.Length).ToArray();
    

    命名空间:

    using System.Linq;
    

    希望对您有所帮助。

    【讨论】:

    • 我应该说不使用任何库,但是谢谢
    • @user3660293 这是 .Net 内置的。
    • @user3660293 只需添加命名空间using System.Linq;
    • 并且没有任何额外的命名空间 *
    【解决方案2】:
    public static int[] countEach(int[][] a) {
        int[] count = new int[a.Length];
        for(int i = 0; i < a.Length; i++){
          count[i] = a[i].Length;
        }
        return count;
    }
    

    【讨论】:

      猜你喜欢
      • 2019-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-06
      相关资源
      最近更新 更多