EnumerateWithIndex<T>()
Enumerate an IEnumerable<T> source and getting the Index and the Item returned in a ValueTuple.
Source
static class Extensions {
public static IEnumerable<(int Index, T Item)> EnumerateWithIndex<T>(this IEnumerable<T> source) {
int index = 0;
foreach (var item in source) {
yield return (index++, item);
}
}
}
Example
var l = new List<Employee> {
new Employee("Fons", 2000),
new Employee("Jim", 4000),
new Employee("Ellen", 3000),
};
foreach (var item in l.EnumerateWithIndex()) {
Console.WriteLine(item.Index);
item.Item.RaiseSalary(10);
Console.WriteLine(item.Item);
}
Author: Fons Sonnemans
Submitted on: 26 jan. 2022
Language: csharp
Type: System.Collections.Generic.IEnumerable<T>
Views: 2379