C# List Index
-
Use the
ElementAt()
Method to Get List Items by Index inC#
-
Use the
List<T>.Item[Int32]
Property to Get List Items by Index inC#
The List<T>
are dynamic array or C++ vector equivalent of C#. It is defined in the System.Collections.Generic
namespace.
It is used to store collections of different types of data, which can then be easily accessed, modified, added, deleted, or sorted. In this tutorial, we will look at how to get list items by index in C#.
Use the ElementAt()
Method to Get List Items by Index in C#
using System;
using System.Linq;
using System.Collections.Generic;
public class Test {
public static void Main() {
var myList = new List<int> { 9, 3, 11, 23, 43 };
var firstItem = myList.ElementAt(0);
Console.WriteLine(firstItem);
}
}
Output:
9
The ElementAt()
method takes the index as an argument and returns the value present at that index inside the list. In the above example, we have shown a sample use case.
Use the List<T>.Item[Int32]
Property to Get List Items by Index in C#
using System;
using System.Linq;
using System.Collections.Generic;
public class Test {
public static void Main() {
var myList = new List<int> { 9, 3, 11, 23, 43 };
var firstItem = myList[0];
Console.WriteLine(firstItem);
}
}
Output:
9
The above example is pretty self-explanatory, where we access the first element of the list myList
using the List<T>.Item[Int32]
property. We can get any index by changing the argument provided from 0
to an index within the range of array size.
Harshit Jindal has done his Bachelors in Computer Science Engineering(2021) from DTU. He has always been a problem solver and now turned that into his profession. Currently working at M365 Cloud Security team(Torus) on Cloud Security Services and Datacenter Buildout Automation.
LinkedIn