Foreach 循环,确定哪个是循环的最后一次迭代 [英] Foreach loop, determine which is the last iteration of the loop

查看:39
本文介绍了Foreach 循环,确定哪个是循环的最后一次迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 Model.Results)
 {
      //if current result is the last item in Model.Results
      //then do something in the code
 }

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

Can I know which loop is last without using for loop and counters?

推荐答案

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

If you just need to do something with the last element (as opposed to something different with the last element then using LINQ will help here:

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

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

If you need to do something different with the last element then you'd need something like:

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() 返回的项目相同.

Though you'd probably need to write a custom comparer to ensure that you could tell that the item was the same as the item returned by Last().

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

This approach should be used with caution as Last may well have to iterate through the collection. While this might not be a problem for small collections, if it gets large it could have performance implications. It will also fail if the list contains duplicate items. In this cases something like this may be more appropriate:

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 循环,确定哪个是循环的最后一次迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆