How to check if a C# list is empty?


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");
      }
   }
}

Updated on: 20-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements