使用“任意”方法查找列表是否为空。
设置列表-
var subjects = new List<string>(); subjects.Add("Maths"); subjects.Add("Java"); subjects.Add("English"); subjects.Add("Science"); subjects.Add("Physics"); subjects.Add("Chemistry");
现在设置以下条件以检查列表是否为空-
bool isEmpty = !subjects.Any(); if(isEmpty) { Console.WriteLine("Empty"); }else { Console.WriteLine("List is not empty"); }
以下是完整的代码-
using System; using System.Collections.Generic; using System.Linq; public class Demo { public static void Main(string[] args) { var subjects = new List<string>(); subjects.Add("Maths"); subjects.Add("Java"); subjects.Add("English"); subjects.Add("Science"); subjects.Add("Physics"); subjects.Add("Chemistry"); foreach (var sub in subjects) { Console.WriteLine(sub); } bool isEmpty = !subjects.Any(); if(isEmpty) { Console.WriteLine("Empty"); } else { Console.WriteLine("List is not empty"); } } }