get element in list c# code example

Example 1: 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

Example 2: c# find element in list of list

var element = (from sublist in userList
               from item in sublist
               where item.uniqueidentifier == someid
               select item).FirstOrDefault();

Example 3: get both item and index in c#

// 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);
}