3 ms·
>It’s super nice to have, and I’m always amazed when languages with “strong” “support” for iteration don’t have it. Like, C# doesn’t. So if you want to iterate
by Arnavion 9y ago
>It’s super nice to have, and I’m always amazed when languages with “strong” “support” for iteration don’t have it. Like, C# doesn’t. So if you want to iterate over a list but also need indices, you need to fall back to a C-style for loop. And if you want to iterate over a lazy or arbitrary iterable but also need indices, you need to track it yourself with a counter.
One of the Enumerable.Select overloads takes a callback that receives both the element and an index. No need to drop down to for loops.
https://msdn.microsoft.com/en-us/library/bb534869 https://msdn.microsoft.com/en-us/library/bb534869
using System;
using System.Linq;
class MainClass
{
public static void Main(string[] args)
{
var list = new[] { "a", "b", "c" };
foreach ((var element, var index) in list.Select((el, i) => (el, i)))
{
Console.WriteLine($"{index}: {element}");
}
}
}
The shorthand syntax for tuples and destructuring is new in C# 7, but the Enumerable.Select overload has existed since the beginning of LINQ. So prior to C# 7 you would have to use an anonymous type or similar to get the same effect.