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

前端 未结 26 942
迷失自我
迷失自我 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:03

    You can make an extension method specially dedicated to this:

    public static class EnumerableExtensions {
        public static bool IsLast(this List items, T item)
            {
                if (items.Count == 0)
                    return false;
                T last = items[items.Count - 1];
                return item.Equals(last);
            }
        }
    

    and you can use it like this:

    foreach (Item result in Model.Results)
    {
        if(Model.Results.IsLast(result))
        {
            //do something in the code
        }
    }
    

提交回复
热议问题