Accessing a List

Different ways of accessing a list in c#

A list can be accessed by following way: 

By Index: 

Indexes of a list starts from zero. We can pass an index number in the square brackets to access individual listitems, like an array. 


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

Using for/foreach loop: 

We can use a for or foreach loop to irerate a List<T> collection.


// for loop
for(int i = 0; i < marks.Count; i++)

// foreach loop
foreach (var mark in marks) {

Using LINQ Method:

There is also the LINQ way for iterating the list.


marks.ForEach(x=> Console.WriteLine(x));

0 Comment's

Comment Form