Thoughts on foreach with Enumerable.Range vs traditional for loop

前端 未结 18 1085
花落未央
花落未央 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 07:07

    I agree that in many (or even most cases) foreach is much more readable than a standard for-loop when simply iterating over a collection. However, your choice of using Enumerable.Range(index, count) isn't a strong example of the value of foreach over for.

    For a simple range starting from 1, Enumerable.Range(index, count) looks quite readable. However, if the range starts with a different index, it becomes less readable because you have to properly perform index + count - 1 to determine what the last element will be. For example…

    // Write the numbers 2 thru 8
    foreach (var index in Enumerable.Range( 2, 7 ))
    {
        Console.WriteLine(index);
    }
    

    In this case, I much prefer the second example.

    // Write the numbers 2 thru 8
    for (int index = 2; index <= 8; index++)
    {
        Console.WriteLine(index);
    }
    

提交回复
热议问题