C#|计算列表中元素的总数

列表 类表示可以通过索引访问的对象列表。它属于 系统收集通用的 名称空间。List类可用于创建不同类型的集合,如整数、字符串等。List类还提供搜索、排序和操作列表的方法。 列表计数属性 用于获取列表中包含的元素总数。

null

属性:

  • 它与阵列不同。A. 列表可以动态调整大小 但数组不能是。
  • List类可以接受null作为引用类型的有效值,并且 允许重复元素 .
  • 如果计数等于容量,则通过重新分配内部数组,列表的容量会自动增加。在添加新元素之前,现有元素将被复制到新数组中。

语法:

list_name.Count

下面的程序演示了Count属性的使用:

例1:

// C# code to get the number of
// elements contained in List
using System;
using System.Collections.Generic;
class Geeks {
// Main Method
public static void Main()
{
// Creating a List of integers
List< int > firstlist = new List< int >();
// adding elements in firstlist
for ( int i = 4; i < 10; i++) {
firstlist.Add(i * 2);
}
// To get the number of
// elements in the List
Console.WriteLine(firstlist.Count);
}
}


输出:

6

例2:

// C# code to get the number of
// elements contained in List
using System;
using System.Collections.Generic;
class Geeks {
// Main Method
public static void Main()
{
// Creating a List of integers
List< int > firstlist = new List< int >();
// To get the number of
// elements in the List
Console.WriteLine(firstlist.Count);
}
}


输出:

0

参考:

© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享