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. 

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

Using for/foreach loop: 

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

Example:

// for loop
for(int i = 0; i < marks.Count; i++)
    Console.WriteLine(marks[i]);

// foreach loop
foreach (var mark in marks) {
    Console.WriteLine(mark);
}

Using LINQ Method:

There is also the LINQ way for iterating the list.

Example:

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

0 Comment's

Comment Form

Submit Comment