Thoughts on foreach with Enumerable.Range vs traditional for loop

前端 未结 18 1402
花落未央
花落未央 2021-01-30 06:13

In C# 3.0, I\'m liking this style:

// Write the numbers 1 thru 7
foreach (int index in Enumerable.Range( 1, 7 ))
{
    Console.WriteLine(index);
}
18条回答
  •  情书的邮戳
    2021-01-30 06:50

    I kind of like the idea. It's very much like Python. Here's my version in a few lines:

    static class Extensions
    {
        public static IEnumerable To(this int from, int to, int step = 1) {
            if (step == 0)
                throw new ArgumentOutOfRangeException("step", "step cannot be zero");
            // stop if next `step` reaches or oversteps `to`, in either +/- direction
            while (!(step > 0 ^ from < to) && from != to) {
                yield return from;
                from += step;
            }
        }
    }
    

    It works like Python's:

    • 0.To(4)[ 0, 1, 2, 3 ]
    • 4.To(0)[ 4, 3, 2, 1 ]
    • 4.To(4)[ ]
    • 7.To(-3, -3)[ 7, 4, 1, -2 ]

提交回复
热议问题