c# list get element by index code example
Example 1: c# find index element array
int[] arr = { 3, 6, 4, 1, 6, 8 };
Array.IndexOf(arr, 6);
Example 2: c# list index
using System.Linq;
var myList = new List<string>{ "Yes", "No", "Maybe"};
var firstItem = myList.ElementAt(0);
Example 3: c# get index of item in list
Array.IndexOf(arrName, searchingFor)
Example 4: find index of string in a list C#
using System;
using System.Collections.Generic;
public class Program {
public static void Main() {
List < string > myList = new List < string > () {
"Football",
"Soccer",
"Tennis",
};
int index = myList.FindIndex(a => a.Contains("Tennis"));
Console.WriteLine("List Item Tennis Found at index: " + index);
}
}
Example 5: get both item and index in c#
public static IEnumerable<(T item, int index)> WithIndex<T>(this IEnumerable<T> source)
{
return source.Select((item, index) => (item, index));
}
foreach (var (item, index) in collection.WithIndex())
{
DoSomething(item, index);
}