IEnumerable foreach, do something different for the last element

后端 未结 5 2210
庸人自扰
庸人自扰 2021-02-20 06:23

I have an IEnumerable. I want to do one thing for each item of the collection, except the last item, to which I want to do something else. How can I code this neatly? I

5条回答
  •  醉酒成梦
    2021-02-20 06:30

    Similar to Marc's answer, but you could write an extension method to wrap it up.

    public static class LastEnumerator
    {
        public static IEnumerable> GetLastEnumerable(this IEnumerable blah)
        {
            bool isFirst = true;
            using (var enumerator = blah.GetEnumerator())
            {
                if (enumerator.MoveNext())
                {
                    bool isLast;
                    do
                    {
                        var current = enumerator.Current;
                        isLast = !enumerator.MoveNext();
                        yield return new MetaEnumerableItem
                            {
                                Value = current,
                                IsLast = isLast,
                                IsFirst = isFirst
                            };
                        isFirst = false;
                    } while (!isLast);
                }
            }
    
        }
    }
    
    public class MetaEnumerableItem
    {
        public T Value { get; set; }
        public bool IsLast { get; set; }
        public bool IsFirst { get; set; }
    }
    

    Then call it like so:

    foreach (var row in records.GetLastEnumerable())
    {
        output(row.Value);
        if(row.IsLast)
        {
            outputLastStuff(row.Value);
        }
    }
    

提交回复
热议问题