Return 一个整数数组,包含每个内部数组 c# 的元素数
Return an array of ints containing the number of elements of each inner array c#
我想编写一个函数,给定输入中的整数数组,returns输出中的整数数组,包含每个内部数组的元素数。
这是我当前的实现:
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#的编程概念。谢谢
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;
}
您可以使用 Linq,通过选择嵌套数组的长度并调用 .ToArray()
将 IEnumerable
转换为 array
:
int[] result = a.Select(x => x.Length).ToArray();
命名空间:
using System.Linq;
希望对您有所帮助。
我想编写一个函数,给定输入中的整数数组,returns输出中的整数数组,包含每个内部数组的元素数。
这是我当前的实现:
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#的编程概念。谢谢
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;
}
您可以使用 Linq,通过选择嵌套数组的长度并调用 .ToArray()
将 IEnumerable
转换为 array
:
int[] result = a.Select(x => x.Length).ToArray();
命名空间:
using System.Linq;
希望对您有所帮助。