Working with the List<T> class in C#

The generic List<T> class is one of the most frequently used generic classes when working with collections in C#. You can use this class to create a collection of any type of object you want. One of the advantages of using the List<T> class is that it can behave both like a list and an array. You can access the records from this list by using the index of the records like you do with arrays.


Suppose you have a class Student with the following data members

class Student  {      public int RollNo;      public string Name;      public String EmailId;  }

If you wish to create a list of students in C# then you will be using the List<T> class in the following manner

List<Student> students = new List<Student>();

By writing this line you have created an empty list of students. To add a new item to the list we use the Add function. For example in the code below we are creating a new object of the Student class and adding it to the students list

// Create a new student object  Student student = new Student();  Student.RollNo = 1;  Student.Name = “Ravinder”;  Student.EmailId = "";    // Add the student to the list  Students.Add(student);

Similarly you can add any number of student objects to this list.

Counting the items in the list

The List<T> class has a Count property using which you can get the total number of items in the list. Look at the code below

int studentsCount = students.Count;

There are many other useful functions in the List<T> class which we will be discussing after discussing about Dictionary and Stack classes

Quick Links



Total Followers
Study Group Created
Study Group Joined
Following Teacher
Following Organization
Blog Articles Added
Questions Asked
Questions Answered
Jobs Posted
Total Members in Group
Questions asked by members
Tasks added in this Group

Please wait..


Login to Open ESchool OR Create your account    Login   SignUp