HOWTO · Csharp
在 C# 中檢查列表是否為空
有兩種主要方法可用於檢查 C# 中的列表是否為空:List.Count 方法和 List.Any()函式。
本頁內容
本教程將介紹在 C# 中檢查列表是否為空的方法。
使用 C# 中的 List.Count 屬性檢查列表是否為空
List.Count 屬性獲得 C# 列表中的元素。如果列表為空,則 List.Count 為 0。以下程式碼示例向我們展示瞭如何使用 C# 中的 List.Count 屬性檢查列表是否為空。
using System;
using System.Collections.Generic;
using System.Linq;
namespace check_empty_list {
class Program {
static void Main(string[] args) {
List<string> emptyList = new List<string>();
if (emptyList.Count == 0) {
Console.WriteLine("List is Empty");
} else {
Console.WriteLine("Not Empty");
}
}
}
}
輸出:
List is Empty
在上面的程式碼中,我們初始化了一個空字串 emptyList 列表,並使用 C# 中的 List.Count 屬性檢查該列表是否為空。
使用 C# 中的 List.Any() 函式檢查列表是否為空
List.Any() 函式也可以用於檢查該列表在 C# 中是否為空。List.Any() 函式的返回型別為布林值。如果列表中有一個元素,則 List.Any() 函式將返回 true;否則返回 false。請參見下面的示例程式碼。
using System;
using System.Collections.Generic;
using System.Linq;
namespace check_empty_list {
class Program {
static void Main(string[] args) {
List<string> emptyList = new List<string>();
if (emptyList.Any()) {
Console.WriteLine("Not Empty");
} else {
Console.WriteLine("List is Empty");
}
}
}
}
輸出:
List is Empty
在上面的程式碼中,我們初始化了一個空字串 emptyList 列表,並使用 C# 中的 List.Any() 函式檢查該列表是否為空。