Getting a list item by index

C#List

C# Problem Overview


I've recently started using c# moving over from Java. I can't seem to find how to get a list item by index. In java to get the first item of the list it would be:

list1.get(0);

What is the equivalent in c#?

C# Solutions


Solution 1 - C#

list1[0];

Assuming list's type has an indexer defined.

Solution 2 - C#

You can use the ElementAt extension method on the list.

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

Solution 3 - C#

Visual Basic, C#, and C++ all have syntax for accessing the Item property without using its name. Instead, the variable containing the List is used as if it were an array:

List[index]

See, for instance, List.Item[Int32] Property.

Solution 4 - C#

Old question, but I see that this thread was fairly recently active, so I'll go ahead and throw in my two cents:

Pretty much exactly what Mitch said. Assuming proper indexing, you can just go ahead and use square bracket notation as if you were accessing an array. In addition to using the numeric index, though, if your members have specific names, you can often do kind of a simultaneous search/access by typing something like:

var temp = list1["DesiredMember"]; The more you know, right?

Solution 5 - C#

.NET List data structure is an Array in a "mutable shell".

So you can use indexes for accessing to it's elements like:

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

Starting with C# 8.0 you can use Index and Range classes for accessing elements. They provides accessing from the end of sequence or just access a specific part of sequence:

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

You can combine indexes and ranges together:

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

Also you can use LINQ ElementAt method but for 99% of cases this is really not necessary and just slow performance solution.

Solution 6 - C#

you can use index to access list elements

List<string> list1 = new List<string>();
list1[0] //for getting the first element of the list

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1909486View Question on Stackoverflow
Solution 1 - C#Mitch WheatView Answer on Stackoverflow
Solution 2 - C#user3004826View Answer on Stackoverflow
Solution 3 - C#Zeyad QuneesView Answer on Stackoverflow
Solution 4 - C#XellarantView Answer on Stackoverflow
Solution 5 - C#picolinoView Answer on Stackoverflow
Solution 6 - C#CodemakerView Answer on Stackoverflow