Neat way to write loop that has special logic for the first item in a collection

后端 未结 12 2644
忘了有多久
忘了有多久 2021-02-13 17:31

Often I have to code a loop that needs a special case for the first item, the code never seems as clear as it should ideally be.

Short of a redesign of the C# language,

12条回答
  •  Happy的楠姐
    2021-02-13 17:45

    Whilst I wouldn't personally do this, there is another way using enumerators, which alleviates the need for conditional logic. Something like this:

    void Main()
    {
        var numbers = Enumerable.Range(1, 5);
        IEnumerator num = numbers.GetEnumerator();
    
        num.MoveNext();
        ProcessFirstItem(num.Current); // First item
    
        while(num.MoveNext()) // Iterate rest
        {
            Console.WriteLine(num.Current);
        }
    
    }
    
        void ProcessFirstItem(object first)
        {
            Console.WriteLine("First is: " + first);
        }
    

    Sample output would be:

    First is: 1
    2
    3
    4
    5
    

提交回复
热议问题