This tutorial will introduce methods to check whether a list is empty or not in C#.

Check Whether a List Is Empty With the List.Count Property in C#

The List.Count property gets the number of elements inside a list in C#. The List.Count is 0 if the list is empty. The following code example shows us how to check whether a list is empty or not with the List.Count property in C#.

using System; using System.Collections.Generic; using System.Linq; namespace check_empty_list { class Program { static void Main(string[] args) { List emptyList = new List(); if(emptyList.Count == 0) { Console.WriteLine("List is Empty"); } else { Console.WriteLine("Not Empty"); } } } }

Output:

List is Empty

In the above code, we initialize an empty list of strings emptyList and check whether the list is empty or not with the List.Count property in C#.

Check Whether a List Is Empty With the List.Any() Function in C#

The List.Any() function can also be used to check whether the list is empty or not in C#. The return type of the List.Any() function is boolean. If there is an element inside the list, the List.Any() function returns true; otherwise, false. See the below example code.

using System; using System.Collections.Generic; using System.Linq; namespace check_empty_list { class Program { static void Main(string[] args) { List emptyList = new List(); if (emptyList.Any()) { Console.WriteLine("Not Empty"); } else { Console.WriteLine("List is Empty"); } } } }

Output:

List is Empty

In the above code, we initialize an empty list of strings emptyList and check whether the list is empty or not with the List.Any() function in C#.

DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Csharp List

  • Convert an IEnumerable to a List in C#
  • C# Remove Item From List
  • C# Join Two Lists Together
  • Create a Comma Separated List in C#
  • Check list empty C#
    report this ad