C# でリストが空かどうかを確認する
Muhammad Maisam Abbas
2024年2月16日
Csharp
Csharp List

このチュートリアルでは、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()
関数を使用してリストが空かどうかを確認します。
チュートリアルを楽しんでいますか? <a href="https://www.youtube.com/@delftstack/?sub_confirmation=1" style="color: #a94442; font-weight: bold; text-decoration: underline;">DelftStackをチャンネル登録</a> して、高品質な動画ガイドをさらに制作するためのサポートをお願いします。 Subscribe
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn