Identifying last loop when using for each

后端 未结 25 1434
眼角桃花
眼角桃花 2020-12-08 09:59

I want to do something different with the last loop iteration when performing \'foreach\' on an object. I\'m using Ruby but the same goes for C#, Java etc.

          


        
25条回答
  •  天命终不由人
    2020-12-08 10:22

    I see a lot of complex, hardly readable code here... why not keep it simple:

    var count = list.Length;
    
    foreach(var item in list)
        if (--count > 0)
            Console.WriteLine("Looping: " + item);
        else
            Console.Writeline("Lastone: " + item);
    

    It's only one extra statement!

    Another common situation is that you want to do something extra or less with the last item, like putting a separator between the items:

    var count = list.Length;
    
    foreach(var item in list)
    {
        Console.Write(item);
        if (--count > 0)
            Console.Write(",");
    }
    

提交回复
热议问题