在 C# 中獲取列表長度
    
    
            Fil Zjazel Romaeus Villegas
    2023年10月12日
    
    Csharp
    Csharp List
    
本教程將演示如何使用 count 函式獲取 C# 列表的長度。
列表是一種指定型別的物件的集合,其值可以通過其索引訪問。
List<T> myList = new List<T>();
只要你新增的值的型別與初始化期間定義的型別匹配,你就可以將任意數量的元素新增到列表中。
C# 列表有一個內建函式 Count,它返回列表中的元素數。
int list_count = myList.Count;
例子:
using System;
using System.Collections.Generic;
namespace ListCount_Example {
  class Program {
    static void Main(string[] args) {
      // Initializing the list of strings
      List<string> student_list = new List<string>();
      // Adding values to the list
      student_list.Add("Anna Bower");
      student_list.Add("Ian Mitchell");
      student_list.Add("Dorothy Newman");
      student_list.Add("Nathan Miller");
      student_list.Add("Andrew Dowd");
      student_list.Add("Gavin Davies");
      student_list.Add("Alexandra Berry");
      // Getting the count of items in the list and storing it in the student_count variable
      int student_count = student_list.Count;
      // Printing the result
      Console.WriteLine("Total Number of students: " + student_count.ToString());
    }
  }
}
上例中初始化了字串列表,並新增了 7 條記錄。新增記錄後,使用 count 函式提取記錄數並將其儲存在一個整數值中,然後列印。
輸出:
Total Number of students: 7
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe