Foreach loop, determine which is the last iteration of the loop

前端 未结 26 981
迷失自我
迷失自我 2020-11-28 02:56

I have a foreach loop and need to execute some logic when the last item is chosen from the List, e.g.:

 foreach (Item result in Mod         


        
26条回答
  •  余生分开走
    2020-11-28 03:13

    Improving Daniel Wolf answer even further you could stack on another IEnumerable to avoid multiple iterations and lambdas such as:

    var elements = new[] { "A", "B", "C" };
    foreach (var e in elements.Detailed())
    {
        if (!e.IsLast) {
            Console.WriteLine(e.Value);
        } else {
            Console.WriteLine("Last one: " + e.Value);
        }
    }
    

    The extension method implementation:

    public static class EnumerableExtensions {
        public static IEnumerable> Detailed(this IEnumerable source)
        {
            if (source == null)
                throw new ArgumentNullException(nameof(source));
    
            using (var enumerator = source.GetEnumerator())
            {
                bool isFirst = true;
                bool hasNext = enumerator.MoveNext();
                int index = 0;
                while (hasNext)
                {
                    T current = enumerator.Current;
                    hasNext = enumerator.MoveNext();
                    yield return new IterationElement(index, current, isFirst, !hasNext);
                    isFirst = false;
                    index++;
                }
            }
        }
    
        public struct IterationElement
        {
            public int Index { get; }
            public bool IsFirst { get; }
            public bool IsLast { get; }
            public T Value { get; }
    
            public IterationElement(int index, T value, bool isFirst, bool isLast)
            {
                Index = index;
                IsFirst = isFirst;
                IsLast = isLast;
                Value = value;
            }
        }
    }
    

提交回复
热议问题