Different ways of accessing a list in c#
A list can be accessed by following way:
Indexes of a list starts from zero. We can pass an index number in the square brackets to access individual listitems, like an array.
Example:
List<int> marks = new List<int>() { 10, 22, 53, 78, 83, 100 }; Console.WriteLine(marks[0]); // prints 10 Console.WriteLine(marks[1]); // prints 22 Console.WriteLine(marks[2]); // prints 53 Console.WriteLine(marks[3]); // prints 78 Console.WriteLine(marks[5]); // prints 100
We can use a for or foreach loop to irerate a List<T> collection.
// for loop for(int i = 0; i < marks.Count; i++) Console.WriteLine(marks[i]); // foreach loop foreach (var mark in marks) { Console.WriteLine(mark); }
There is also the LINQ way for iterating the list.
marks.ForEach(x=> Console.WriteLine(x));