Yaroslav Holod
0
Q:

c# list index

// 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
3
// You can index a List using listName[int]
List<string> stringList = new List<string>{"string1", "string2"};
string name = stringList[1];
// Output:
// "string2"
2
// add this to your namespace
public static IEnumerable<(T item, int index)> WithIndex<T>(this IEnumerable<T> source)
{
    return source.Select((item, index) => (item, index));
}

//do something like this

foreach (var (item, index) in collection.WithIndex())
{
    DoSomething(item, index);
}
1

New to Communities?

Join the community