How to check if a C# list is empty?

CsharpProgrammingServer Side Programming

Use the Any method to find whether the list is empty or not.

Set the list −

var subjects = new List<string>();
subjects.Add("Maths");
subjects.Add("Java");
subjects.Add("English");
subjects.Add("Science");
subjects.Add("Physics");
subjects.Add("Chemistry");

Now set the following condition to check whether the list is empty or not −

bool isEmpty = !subjects.Any();
if(isEmpty) {
      Console.WriteLine("Empty");
   }else {
      Console.WriteLine("List is not empty");
   }

The following is the complete code −

Example

 Live Demo

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");
      }
   }
}
raja
Published on 08-Aug-2018 12:35:06
Advertisements