Identifying last loop when using for each [duplicate]

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(",");
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)