Skip to content
Related Articles

Related Articles

C# | Count the total number of elements in the List
  • Difficulty Level : Expert
  • Last Updated : 01 Feb, 2019

List class represents the list of objects which can be accessed by index. It comes under the System.Collection.Generic namespace. List class can be used to create a collection of different types like integers, strings etc. List class also provides the methods to search, sort, and manipulate lists. List.Count Property is used to get the total number of elements contained in the List.

Properties:

  • It is different from the arrays. A list can be resized dynamically but arrays cannot be.
  • List class can accept null as a valid value for reference types and it also allows duplicate elements.
  • If the Count becomes equals to Capacity then the capacity of the List increases automatically by reallocating the internal array. The existing elements will be copied to the new array before the addition of the new element.

Syntax:

list_name.Count

Below programs illustrate the use of Count property:

Example 1:






// C# code to get the number of
// elements contained in List
using System;
using System.Collections.Generic;
  
class Geeks {
  
    // Main Method
    public static void Main()
    {
  
        // Creating a List of integers
        List<int> firstlist = new List<int>();
  
        // adding elements in firstlist
        for (int i = 4; i < 10; i++) {
            firstlist.Add(i * 2);
        }
  
        // To get the number of
        // elements in the List
        Console.WriteLine(firstlist.Count);
    }
}


Output:

6

Example 2:




// C# code to get the number of
// elements contained in List
using System;
using System.Collections.Generic;
  
class Geeks {
  
    // Main Method
    public static void Main()
    {
  
        // Creating a List of integers
        List<int> firstlist = new List<int>();
  
        // To get the number of
        // elements in the List
        Console.WriteLine(firstlist.Count);
    }
}


Output:

0

Reference:

My Personal Notes arrow_drop_up
Recommended Articles
Page :