1.

Check whether a list is empty or not in C#

Answer»

The Count property can be used to check if a list is empty or not. This property GETS the number of elements in the list. So, if the Count property gives 0 for a list, this means that the list is empty.

A program that checks if the list is empty or not using the Count property in C# is given as follows:

using System; using System.Collections.Generic; CLASS Demo {    public static void Main()    {        List<INT> list1 = new List<int>();        List<int> list2 = new List<int>();        list1.Add(7);        list1.Add(1);        list1.Add(5);        list1.Add(9);        list1.Add(3);        if (list1.Count == 0)        {            Console.WriteLine("List 1 is empty");        }        else        {            Console.WriteLine("The elements in List 1 are:");            foreach (int i in list1)            {                Console.WriteLine(i);            }        }        if (list2.Count == 0)        {            Console.WriteLine("List 2 is empty");        }        else        {            Console.WriteLine("The elements in List 2 are:");            foreach (int i in list2)            {                Console.WriteLine(i);            }        }    } }

The output of the above program is as follows:

The elements in List 1 are: 7 1 5 9 3 List 2 is empty

In the above program, if the list is empty then that is printed. Otherwise all the list elements are printed.



Discussion

No Comment Found