The Complete Guide to Getting List Values by Index in C#

Direct Access: Unleashing the Power of []
The most straightforward way to grab a list element by its index is using the [] operator.
List<string> names = new List<string>() { "Alice", "Bob", "Charlie" };
string name = names[0]; // Accesses the first element ("Alice")
Direct indexing with [] offers high performance due to its direct memory access. You’ll get an IndexOutOfRangeException if you try to access an index that’s outside the bounds of the list – less than 0 or greater than or equal to the list’s Count. To avoid IndexOutOfRangeException, always check the list’s Count property before accessing elements and use conditional statements to ensure the index is within the valid range.
The following code demonstrates how to avoid IndexOutOfRangeException by checking the list’s Count property before accessing elements.
List<int> numbers = new List<int>() { 10, 20, 30 };
if (numbers.Count > 0 && 1 < numbers.Count)
{
int secondNumber = numbers[1]; // Accesses the second element (20)
Console.WriteLine(secondNumber);
}
Using the ElementAt() Method
The ElementAt() method, provided by LINQ, is another way to access list elements by index.
using System.Linq;
List<string> colors = new List<string>() { "Red", "Green", "Blue" };
string color = colors.ElementAt(2); // Accesses the third element ("Blue")
ElementAt() throws an ArgumentOutOfRangeException if the index is out of range, just like the [] operator. It’s generally slower than [] due to the overhead of a method call. Some developers find it more readable, especially when needing to handle potential out-of-range exceptions.
To handle out-of-range exceptions gracefully, use ElementAtOrDefault(). This method returns a default value (e.g., null for reference types, 0 for integers) if the index is out of range, preventing an exception.
using System.Linq;
List<string> fruits = new List<string>() { "Apple", "Banana" };
string fruit = fruits.ElementAtOrDefault(5); // fruit will be null
Now, let’s check if fruit is null and handle the case where the index was out of range.
if (fruit != null)
{
Console.WriteLine(fruit);
}
else
{
Console.WriteLine("Index was out of range.");
}
ElementAt() or ElementAtOrDefault() are good choices when you want cleaner code or need to handle out-of-range scenarios without explicit checks.
Implementing Custom Index Validation
For extra safety and clarity, especially in larger projects, consider implementing custom index validation.
Extension methods can provide a more readable and reusable way to access list elements with built-in validation.
Here’s a TryGetElementAt() extension method:
using System;
using System.Collections.Generic;
public static class ListExtensions
{
public static bool TryGetElementAt<T>(this List<T> list, int index, out T result)
{
if (index >= 0 && index < list.Count)
{
result = list[index];
return true;
}
result = default(T);
return false;
}
}
List<int> values = new List<int>() { 1, 2, 3 };
if (values.TryGetElementAt(1, out int value))
{
Console.WriteLine(value); // Output: 2
}
else
{
Console.WriteLine("Index out of range.");
}
This TryGetElementAt method encapsulates the index validation logic, making your code cleaner and more robust.
Custom validation gives you:
Create a free account, or log in.
Gain access to free articles, game development tools, and game assets.