EN
C# / .NET - check if List is empty
0 points
In this article, we would like to show you how to check if List is empty in C#.
Quick solution:
xxxxxxxxxx
1
List<int> list = new List<int>();
2
3
bool isEmpty = !list.Any();
4
5
Console.WriteLine(isEmpty); // Output: True
or:
xxxxxxxxxx
1
List<int> list = new List<int>();
2
3
bool isEmpty = list.Count() == 0;
4
5
Console.WriteLine(isEmpty); // Output: True
In this example, we check if list is empty using Any()
method from System.Linq
.
xxxxxxxxxx
1
using System;
2
using System.Linq;
3
using System.Collections.Generic;
4
5
public class Program
6
{
7
public static void Main()
8
{
9
List<int> list1 = new List<int>();
10
List<int> list2 = new List<int> { 1, 2, 3 };
11
12
Console.WriteLine(isEmpty(list1)); // Output: True
13
Console.WriteLine(isEmpty(list2)); // Output: False
14
}
15
16
private static bool isEmpty(List<int> list)
17
{
18
return !list.Any();
19
}
20
}
Output:
xxxxxxxxxx
1
True
2
False
In this example, we check if list is empty using List.Count
property.
xxxxxxxxxx
1
using System;
2
using System.Collections.Generic;
3
4
public class Program
5
{
6
public static void Main()
7
{
8
List<int> list1 = new List<int>();
9
List<int> list2 = new List<int> { 1, 2, 3 };
10
11
Console.WriteLine(isEmpty(list1)); // Output: True
12
Console.WriteLine(isEmpty(list2)); // Output: False
13
}
14
15
private static bool isEmpty(List<int> list)
16
{
17
return list.Count == 0;
18
}
19
}
Output:
xxxxxxxxxx
1
True
2
False