Check if a list is empty in C#
This post will discuss how to determine whether a list is empty in C#. The solution should return true if the list contains any elements; otherwise, false.
1. Using Enumerable.Any() method (System.Linq)
To determine whether a list contains any elements, we can use the Enumerable.Any() method. The following example demonstrates this use of Any.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
using System; using System.Collections.Generic; using System.Linq; public class Example { public static bool IsEmpty<T>(List<T> list) { if (list == null) { return true; } return !list.Any(); } public static void Main() { List<int> list = new List<int>(); bool isEmpty = IsEmpty(list); if (isEmpty) { Console.WriteLine("List is Empty"); } else { Console.WriteLine("List contains elements"); } } } /* Output: List is Empty */ |
2. Using Enumerable.FirstOrDefault() method (System.Linq)
The Enumerable.FirstOrDefault() method returns the first element of a sequence. If no elements are found, FirstOrDefault returns a default value. We can use this to check for an empty list as follows:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static bool IsEmpty<T>(List<T> list) { if (list == null) { return true; } return list.FirstOrDefault() != null; } public static void Main() { List<int> list = new List<int>(); bool isEmpty = IsEmpty(list); if (isEmpty) { Console.WriteLine("List is Empty"); } else { Console.WriteLine("List contains elements"); } } } /* Output: List is Empty */ |
3. Using Enumerable.Count() method (System.Linq)
Another approach is to use the Enumerable.Count() method, which returns the total number of elements in a sequence.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
using System; using System.Collections.Generic; public class Example { public static bool IsEmpty<T>(List<T> list) { if (list == null) { return true; } return list.Count == 0; } public static void Main() { List<int> list = new List<int>(); bool isEmpty = IsEmpty(list); if (isEmpty) { Console.WriteLine("List is Empty"); } else { Console.WriteLine("List contains elements"); } } } /* Output: List is Empty */ |
That’s all about determining whether a list is empty in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)