Coder Perfect

Obtaining a list item using the index

Problem

I recently switched from Java to C# and am enjoying it. I’m having trouble finding a way to get a list item by index. To obtain the first item in the list in Java, type:

list1.get(0);

What is the c# equivalent?

Asked by user1909486

Solution #1

list1[0];

Assume that the list type has an indexer defined.

Answered by Mitch Wheat

Solution #2

On the list, you can use the ElementAt extension method.

For example:

// Get the first item from the list

using System.Linq;

var myList = new List<string>{ "Yes", "No", "Maybe"};
var firstItem = myList.ElementAt(0);

// Do something with firstItem

Answered by user3004826

Solution #3

The Item property can be accessed without specifying its name in Visual Basic, C#, and C++. Instead, the List is stored in a variable that is treated as an array.

List[index]

For example, go to https://msdn.microsoft.com/en-us/library/0ebtbkkc(v=vs.110).aspx.

Answered by Zeyad Qunees

Solution #4

Although this is an old question, I see that this forum was recently active, so I’ll add my two cents:

That’s very much what Mitch said. You can just use square bracket notation as if you were accessing an array, assuming sufficient indexing. If your members have specific names, in addition to utilizing the numeric index, you may typically perform a simultaneous search/access by typing something like:

var temp = list1["DesiredMember"];

Isn’t it true that the more you know, the better?

Answered by Xellarant

Solution #5

In a “mutable shell,” the.NET List data structure is an Array.

As a result, indexes can be used to retrieve its elements, such as:

var firstElement = myList[0];
var secondElement = myList[1];

You can use the Index and Range classes to access elements starting with C# 8.0. They allow you to access the sequence from the beginning or only a certain section of it:

var lastElement = myList[^1]; // Using Index
var fiveElements = myList[2..7]; // Using Range, note that 7 is exclusive

You can combine indexes and ranges in the following way:

var elementsFromThirdToEnd = myList[2..^0]; // Index and Range together

You can also use the LINQ ElementAt method, although this isn’t essential in 99 percent of circumstances and is just a slow performance solution.

Answered by picolino

Post is based on https://stackoverflow.com/questions/15456845/getting-a-list-item-by-index