Post

For Each IEnumerator Extension

1
2
3
4
5
6
7
8
9
10
11
12
13
public static IEnumerator GetEnumerator(this System.ValueTuple<int, int, int> range)
{
    int start = range.Item1;
    int end = range.Item2;
    int step = range.Item3;

    if (step > 0)
        for (int i = start; i <= end; i += step)
            yield return i;
    else
        for (int i = start; i >= end; i += step)
            yield return i;
}
1
2
foreach (int i in (-10, 10, 3))
    Console.WriteLine(i);
1
2
3
4
5
6
7
8
9
Imports Tools.Extensions

Public Module Program
  Sub Main()
    For Each i In (1, 10, 2)
      Console.WriteLine(i)
    Next
  End Sub
End Module
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
Imports System
Imports System.Runtime.CompilerServices
Imports System.Collections
				
Public Module Module1
	Public Sub Main()
		For Each i in (1, 10, 2)
			Console.WriteLine(i)
		Next
	End Sub
End Module

Public Module Tools
    <Extension>
	Public Iterator Function GetEnumerator(range As ValueTuple(Of Integer, Integer, Integer)) As IEnumerator
        Dim start = range.Item1
        Dim [end] = range.Item2
        Dim [step] = range.Item3

        If ([step] > 0) Then
            For i = start To [end] Step [step]
                Yield i
            Next
        Else
            For i = start To [end] Step [step]
                Yield i
            Next
        End If
    End Function

End Module
This post is licensed under CC BY 4.0 by the author.