Thoughts on foreach with Enumerable.Range vs traditional for loop

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

    This is just for fun. (I'd just use the standard "for (int i = 1; i <= 10; i++)" loop format myself.)

    foreach (int i in 1.To(10))
    {
        Console.WriteLine(i);    // 1,2,3,4,5,6,7,8,9,10
    }
    
    // ...
    
    public static IEnumerable To(this int from, int to)
    {
        if (from < to)
        {
            while (from <= to)
            {
                yield return from++;
            }
        }
        else
        {
            while (from >= to)
            {
                yield return from--;
            }
        }
    }
    

    You could also add a Step extension method too:

    foreach (int i in 5.To(-9).Step(2))
    {
        Console.WriteLine(i);    // 5,3,1,-1,-3,-5,-7,-9
    }
    
    // ...
    
    public static IEnumerable Step(this IEnumerable source, int step)
    {
        if (step == 0)
        {
            throw new ArgumentOutOfRangeException("step", "Param cannot be zero.");
        }
    
        return source.Where((x, i) => (i % step) == 0);
    }
    

提交回复
热议问题