Accessing elements of a list using foreach loop

Now that you know how to create a collection in C# using the List<T> class you will feel the need to be able to access the elements you have added to the collection. The most common method of accessing the elements from a list is to use a special loop called the foreach loop. The foreach loop works very well with collections. It gives you a pointer to each element of the collection one at a time and using that pointer you can access the data and methods of that object.

Foreach loop syntax

Suppose we have a List of students and we want to use the foreach loop to iterate over all students and print their names on the console window. This is a perfect case to use the foreach loop. Look at the code below

class Student  {      public int RollNo;      public string Name;      public String EmailId;  }    class Program  {      static void Main(string[] args)      {          List<Student> allStudents = new List<Student>();            // Code to fill the list with student objects.            // Iterating over the collection using foreach loop          foreach(Student s1 in allStudents)          {              Console.WriteLine(s1.Name);          }      }  }

In the above code look at the syntax of the foreach loop. In this loop we have created a pointer s1 of the Student class and allStudents is the collection of the Student objects. Inside the foreach loop we are using the s1 pointer to access the name property of the student object to which the pointer is pointing to. This loop will run for all the objects in the collection, pointing to one object at a time.

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