Identifying last loop when using for each

后端 未结 25 1391
眼角桃花
眼角桃花 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:25

    If you're using a collection that exposes a Count property - an assumption made by many of the other answers, so I'll make it too - then you can do something like this using C# and LINQ:

    foreach (var item in list.Select((x, i) => new { Val = x, Pos = i }))
    {
        Console.Write(item.Pos == (list.Count - 1) ? "Last one: " : "Looping: ");
        Console.WriteLine(item.Val);
    }
    

    If we additionally assume that the items in the collection can be accessed directly by index - the currently accepted answer assumes this - then a plain for loop will be more elegant/readable than a foreach:

    for (int i = 0; i < list.Count; i++)
    {
        Console.Write(i == (list.Count - 1) ? "Last one: " : "Looping: ");
        Console.WriteLine(list[i]);
    }
    

    If the collection doesn't expose a Count property and can't be accessed by index then there isn't really any elegant way to do this, at least not in C#. A bug-fixed variation of Thomas Levesque's answer is probably as close as you'll get.


    Here's the bug-fixed version of Thomas's answer:

    string previous = null;
    bool isFirst = true;
    foreach (var item in list)
    {
        if (!isFirst)
        {
            Console.WriteLine("Looping: " + previous);
        }
        previous = item;
        isFirst = false;
    }
    if (!isFirst)
    {
        Console.WriteLine("Last one: " + previous);
    }
    

    And here's how I would do it in C# if the collection doesn't expose a Count property and the items aren't directly accessible by index. (Notice that there's no foreach and the code isn't particularly succinct, but it will give decent performance over pretty much any enumerable collection.)

    // i'm assuming the non-generic IEnumerable in this code
    // wrap the enumerator in a "using" block if dealing with IEnumerable<T>
    var e = list.GetEnumerator();
    if (e.MoveNext())
    {
        var item = e.Current;
    
        while (e.MoveNext())
        {
            Console.WriteLine("Looping: " + item);
            item = e.Current;
        }
        Console.WriteLine("Last one: " + item);
    }
    
    0 讨论(0)
提交回复
热议问题