库函数参考

元素个数

数一数列表里有几个元素。即使值相同,每个位置也要算一次。

values.Length

简单示例

初始状态4 4 7
结果3
Program.cs
using System;

int[] values = new int[] { 4, 4, 7 };
Console.WriteLine(values.Length);
输出
3
广告

生活中的例子

送货清单上的包裹编号是 41、17 和 63。一共要送几个包裹?

初始状态41 17 63
结果3
Program.cs
using System;

int[] parcels = new int[] { 41, 17, 63 };
Console.WriteLine(parcels.Length);
输出
3

乘客名单里有 8 号和 11 号两张车票。名单里有几位乘客?

初始状态8 11
结果2
Program.cs
using System;

int[] tickets = new int[] { 8, 11 };
Console.WriteLine(tickets.Length);
输出
2

四次测验的分数是 2、2、5 和 3。相同分数也分别计数,一共有几次测验记录?

初始状态2 2 5 3
结果4
Program.cs
using System;

int[] scores = new int[] { 2, 2, 5, 3 };
Console.WriteLine(scores.Length);
输出
4

空列表里没有元素,所以长度为零。列表的长度就是里面的元素个数。

运行示例
终端
dotnet new console --output Lesson
cp Program.cs Lesson/Program.cs
dotnet run --project Lesson
官方文档