我有一个foreach
循环,当从List
中 Select 最后一项时,需要执行一些逻辑,例如:
foreach (Item result in Model.Results)
{
//if current result is the last item in Model.Results
//then do something in the code
}
如果不使用FOR循环和计数器,我可以知道最后是哪个循环吗?
我有一个foreach
循环,当从List
中 Select 最后一项时,需要执行一些逻辑,例如:
foreach (Item result in Model.Results)
{
//if current result is the last item in Model.Results
//then do something in the code
}
如果不使用FOR循环和计数器,我可以知道最后是哪个循环吗?
如果您只需要对最后一个元素执行某些操作(而不是对最后一个元素执行different),那么使用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
}
}