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.
using System.Collections.Generic; public static bool IsEmpty[List list] public static void Main[] List list = new List[]; bool isEmpty = IsEmpty[list]; Console.WriteLine["List is Empty"]; Console.WriteLine["List contains elements"]; |
Download Run Code
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:
using System.Collections.Generic; public static bool IsEmpty[List list] return list.FirstOrDefault[] != null; public static void Main[] List list = new List[]; bool isEmpty = IsEmpty[list]; Console.WriteLine["List is Empty"]; Console.WriteLine["List contains elements"]; |
Download Run Code
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.
using System.Collections.Generic; public static bool IsEmpty[List list] public static void Main[] List list = new List[]; bool isEmpty = IsEmpty[list]; Console.WriteLine["List is Empty"]; Console.WriteLine["List contains elements"]; |
Download Run Code
That’s all about determining whether a list is empty in C#.
Thanks for reading.
Please use our online compiler to post code in comments using C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and help us grow. Happy coding 🙂