.NET 9 —LINQ — New Index Method

Henrique Siebert Domareski
3 min readNov 11, 2024

--

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:

foreach ((int index, City city) in cities.Index())
{
Console.WriteLine($"Index: {index}, City: {city.Name}");
}

Note that the Index method returns a tuple, where the first value is the index, and the second value is the element itself. The output is:

Index: 0, City: Paris
Index: 1, City: Berlin
Index: 2, City: Madrid
Index: 3, City: Rome
Index: 4, City: Amsterdam

Another way to achieve the same result

In previous .NET version, we could also achieve the same result by using Count and a traditional loop with a for:

var citiesCount = cities.Count();

for (int i = 0; i < citiesCount; i++)
{
Console.WriteLine($"Index: {i}, City: {cities[i].Name}");
}

Another way is by using the Select method from LINQ, to get the indexed elements of the collection, and iterate over it by using a foreach loop:

var indexedElements = cities.Select((item, index) => 
new { Index = index, Item = item });

foreach (var item in indexedElements)
{
Console.WriteLine($"Index: {item.Index}, City: {item.Item.Name}");
}

In both cases, the output will be the same as the example with the Index method.

Benchmark

Thinking about performance, I ran a benchmark using a list with 100.000 records, for these three different approaches that I previously presented, and you can see the results below:

| Method                | Mean    | Error   | StdDev  | Rank |
|---------------------- |--------:|--------:|--------:|-----:|
| 'New Index method' | 11.33 s | 0.224 s | 0.209 s | 1 |
| 'Select with foreach' | 11.51 s | 0.202 s | 0.189 s | 1 |
| 'For loop with Count' | 12.42 s | 0.239 s | 0.200 s | 2 |
  • The new Index method performed fastest, yielding a slight advantage in execution time and earning the top rank in terms of efficiency.
  • The method using a Select combined with a foreach loop performed comparably to the new Index method with only a minor difference in execution speed.
  • The traditional approach using Count and a for loop, was only slightly slower than the other methods, showing a minor difference in performance.

Conclusion

The Index method allows you to return index positions of items in a list in an easy and efficient way. When comparing this method with other ways to do the same thing, the performance is quite similar, but still slightly better. If the objective is maximum efficiency, even small differences can matter, especially if you are working with high-frequency access. Beyond that, this approach can make your code simpler and easier to read.

This is the link for the project in GitHub: https://github.com/henriquesd/LINQIndexDotNet9

If you like this demo, I kindly ask you to give a ⭐️ in the repository.

Thanks for reading!

References

Now it is running without the console option

--

--

No responses yet