Home » C#.Net

Gets the number of elements contained in the List<T> in C#

C# | Count total number of list elements: Here, we are going to learn how to count total number of elements of a list using List.Count property?
Submitted by IncludeHelp, on March 11, 2019

Given a list, and we have to count its total number of elements using List.Count property.

C# List

A list is used to represent the list of the objects, it is represented as List<T>, where T is the type of the list objects/elements.

A list is a class which comes under System.Collections.Generic package, so we have to include it first.

List.Count property

Count is a property of List class; it returns the total number of elements of a List.

Syntax:

    List_name.Count;

Here, List_name is the name of input/source list whose elements to be counted.

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 of a 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
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.