foreach 循环,判断哪个是循环的最后一次迭代

问题描述

如果您只需要对最后一个元素做一些事情(而不是对最后一个元素做一些 的事情,那么使用 LINQ 将在这里有所帮助:

Item last = Model.Results.Last();
// do something with last

如果您需要对最后一个元素做一些不同的事情,那么您需要类似的东西:

Item last = Model.Results.Last();
foreach (Item result in Model.Results)
{
    // do something with each item
    if (result.Equals(last))
    {
        // do something different with the last item
    }
    else
    {
        // do something different with every item but the last
    }
}

尽管您可能需要编写一个自定义比较器以确保您可以分辨出该项目与Last().

应谨慎使用此方法,因为Last可能必须遍历集合。虽然这对于小型集合来说可能不是问题,但如果它变得很大,它可能会对性能产生影响。如果列表包含重复项,它也会失败。在这种情况下,这样的事情可能更合适:

int totalCount = result.Count();
for (int count = 0; count < totalCount; count++)
{
    Item result = Model.Results[count];

    // do something with each item
    if ((count + 1) == totalCount)
    {
        // do something different with the last item
    }
    else
    {
        // do something different with every item but the last
    }
}

解决方法

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

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

如果不使用 for 循环和计数器,我可以知道哪个循环是最后一个吗?