我有一个foreach循环,需要执行一些逻辑时,最后一项是从列表中选择,例如:

 foreach (Item result in Model.Results)
 {
      //if current result is the last item in Model.Results
      //then do something in the code
 }

我可以知道哪个循环是最后没有使用循环和计数器吗?


当前回答

     List<int> ListInt = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };


                int count = ListInt.Count;
                int index = 1;
                foreach (var item in ListInt)
                {
                    if (index != count)
                    {
                        Console.WriteLine("do something at index number  " + index);
                    }
                    else
                    {
                        Console.WriteLine("Foreach loop, this is the last iteration of the loop " + index);
                    }
                    index++;

                }
 //OR
                int count = ListInt.Count;
                int index = 1;
                foreach (var item in ListInt)
                {
                    if (index < count)
                    {
                        Console.WriteLine("do something at index number  " + index);
                    }
                    else
                    {
                        Console.WriteLine("Foreach loop, this is the last iteration of the loop " + index);
                    }
                    index++;

                }

其他回答

正如Chris所展示的,Linq可以工作;只需使用Last()来获得枚举对象中最后一个的引用,只要你没有使用该引用,那么就执行正常的代码,但如果你正在使用该引用,那么就执行额外的事情。它的缺点是它总是O(N)-复杂度。

你可以使用Count()(如果IEnumerable也是一个ICollection, Count()是O(1);这对于大多数常见的内置IEnumerables都是正确的),并将foreach与计数器混合:

var i=0;
var count = Model.Results.Count();
foreach (Item result in Model.Results)
{
    if (++i == count) //this is the last item
}

你可以这样做:

foreach (DataGridViewRow dgr in product_list.Rows)
{
    if (dgr.Index == dgr.DataGridView.RowCount - 1)
    {
        //do something
    }
}

你可以只使用一个for循环,不需要在for体中添加额外的if:

for (int i = 0; i < Model.Results.Count - 1; i++) {
    var item = Model.Results[i];
}

for条件中的-1负责跳过最后一项。

接受的答案将不适用于集合中的副本。如果设置在foreach上,则可以添加自己的索引变量。

int last = Model.Results.Count - 1;
int index = 0;
foreach (Item result in Model.Results)
{
    //Do Things

    if (index == last)
        //Do Things with the last result

    index++;
}

在某些类型上使用Last()将遍历整个集合! 这意味着如果执行foreach并调用Last(),则循环两次!我相信你会尽量避免大量收藏。

那么解决方案是使用while循环:

using var enumerator = collection.GetEnumerator();

var last = !enumerator.MoveNext();
T current;

while (!last)
{
  current = enumerator.Current;        

  //process item

  last = !enumerator.MoveNext();        
  if(last)
  {
    //additional processing for last item
  }
}

因此,除非集合类型为IList<T>,否则Last()函数将遍历所有集合元素。

Test

如果你的集合提供了随机访问(例如实现了IList<T>),你也可以像下面这样检查你的项目。

if(collection is IList<T> list)
  return collection[^1]; //replace with collection.Count -1 in pre-C#8 apps