c# list index code example

Example 1: c# list index

// Get the first item from the list

using System.Linq;

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

// Do something with firstItem

Example 2: c sharp list indexer

// You can index a List using listName[int]
List stringList = new List{"string1", "string2"};
string name = stringList[1];
// Output:
// "string2"

Example 3: get both item and index in c#

// add this to your namespace
public static IEnumerable<(T item, int index)> WithIndex(this IEnumerable source)
{
    return source.Select((item, index) => (item, index));
}

//do something like this

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

Example 4: c# list any retun indec

public class Item {
	public int Id { get; set; }
	public Item() {}
	public Item(int id) { Id = id; }
}
List idList = { new Item(1), new Item(2), new Item(3) };
Item[] idLArr = [ new Item(1), new Item(2), new Item(3) ];

Item newItem = new Item(1);

// Using a lambda expression we can do the following query
int index = idList.FindIndex(item => item.Id == newItem.Id);
int arrIndex = Array.IndexOf(idLArr, newItem.Id);

//Then use it like so:
if (index != -1)
{
	// The item exists at index 0!
}

Tags:

Misc Example