问题描述
我有一个的foreach
循环,需要执行一些逻辑,当最后一个项目从列表
选择,例如:
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
}
我可以知道哪个循环是最后不使用循环和计数器?
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
}
}
虽然你可能需要编写一个自定义比较,以确保您能告诉该项目是一样通过退回产品的最后()
。
此方法应谨慎使用,因为最后
可能不得不通过集合进行迭代。虽然这可能不是小集合的一个问题,如果它得到大型它可能会影响性能。
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.
这篇关于foreach循环,确定哪个是循环的最后一次迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!