Foreach loop, determine which is the last iteration of the loop
I have a foreach
loop and need to execute some logic when the last item is chosen from the List
, eg:
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?
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
}
}
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()
.
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.
How about a good old fashioned for loop?
for (int i = 0; i < Model.Results.Count; i++) {
if (i == Model.Results.Count - 1) {
// this is the last item
}
}
Or using Linq and the foreach:
foreach (Item result in Model.Results)
{
if (Model.Results.IndexOf(result) == Model.Results.Count - 1) {
// this is the last item
}
}
As Chris shows, Linq will work; just use Last() to get a reference to the last one in the enumerable, and as long as you aren't working with that reference then do your normal code, but if you ARE working with that reference then do your extra thing. Its downside is that it will always be O(N)-complexity.
You can instead use Count() (which is O(1) if the IEnumerable is also an ICollection; this is true for most of the common built-in IEnumerables), and hybrid your foreach with a counter:
var i=0;
var count = Model.Results.Count();
foreach (Item result in Model.Results)
{
if(++i==count) //this is the last item
}
链接地址: http://www.djcxy.com/p/52970.html