C# | Count the total number of elements in the List

In this tutorial, we will learn how to count the total number of elements in the List using C# program? By IncludeHelp Last updated : April 15, 2023

Given a C# list, the task is that we have to count its total number of elements.

How to count the total number of List elements?

To count the total number of List elements, use List<T>.Count property, it called with the List name and returns the number of elements contained in the List<T>.

Syntax

public int Count { get; }

Example

Input:
//an integer list
List<int> int_list = new List<int> { 10, 20, 30, 40, 50, 60, 70 };

//a string list 
List<string> str_list = new List<string>{
    "Manju", "Amit", "Abhi", "Radib", "Prem"
};

Function call:
int_list.Count;
str_list.Count;

Output:
7
5

C# program to count the total number of elements in the List

using System;
using System.Text;
using System.Collections.Generic;

namespace Test {
  class Program {
    static void Main(string[] args) {
      //an integer list
      List <int> int_list = new List <int> {10, 20, 30, 40, 50, 60, 70};

      //a string list 
      List <string> str_list = new List <string> {
        "Manju",
        "Amit",
        "Abhi",
        "Radib",
        "Prem"
      };

      //printing total number of elements
      Console.WriteLine("Total elements in int_list is: " + int_list.Count);
      Console.WriteLine("Total elements in str_list is: " + str_list.Count);

      //hit ENTER to exit
      Console.ReadLine();
    }
  }
}

Output

Total elements in int_list is: 7
Total elements in str_list is: 5



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.