Thoughts on foreach with Enumerable.Range vs traditional for loop

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

    Strictly speaking, you misuse enumeration.

    Enumerator provides the means to access all the objects in a container one-by-one, but it does not guarantee the order.

    It is OK to use enumeration to find the biggest number in an array. If you are using it to find, say, first non-zero element, you are relying on the implementation detail you should not know about. In your example, the order seems to be important to you.

    Edit: I am wrong. As Luke pointed out (see comments) it is safe to rely on the order when enumerating an array in C#. This is different from, for example, using "for in" for enumerating an array in Javascript .

提交回复
热议问题