Sitemap

.NET 9 —LINQ — New Index Method

2 min readNov 11, 2024

--

Press enter or click to view image in full size

⚠️ This article has moved to my website.

You can read the latest version here:
👉 https://henriquesd.com/articles/net-9-linq-new-index-method

Below is a short preview of the article.

With .NET 9, the new LINQ method Index (Index<TSource>(IEnumerable<TSource>) was introduced. With this method you can easily extract the implicit index of an Enumerable.

In a previous article, I demonstrated the three new LINQ methods that were added in .NET 9: CountBy, AggregateBy and Index. In this article, I’d like to focus on the Index method and demonstrate alternative ways to achieve similar results in earlier .NET versions, alongside with a benchmark to compare performance.

The Index method

The Index method returns a tuple (IEnumerable<(int Index, TSource Item)>), where the first value is the Index and the second is the Element in the collection.

To demonstrate how this method works, I created a list of cities, which will be used in the examples below:

public class City
{
public string Name { get; set; }
public string Country { get; set; }

public City(string name, string country)
{
Name = name;
Country = country;
}
}

var cities = new List<City>()
{
new City("Paris", "France"),
new City("Berlin", "Germany"),
new City("Madrid", "Spain"),
new City("Rome", "Italy"),
new City("Amsterdam", "Netherlands")
};

With the Index method, we can easy retrieve the index and the element of a list, using a foreach loop:

👉 Continue reading the full article here: https://henriquesd.com/articles/net-9-linq-new-index-method

--

--