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 Mod
You could just use a for loop and there is no need to add an extra if
inside the for
body:
for (int i = 0; i < Model.Results.Count - 1; i++) {
var item = Model.Results[i];
}
The -1
in the for
condition takes care of skipping the last item.
The accepted answer will not work for duplicates in the collection. If you're set on the foreach
, you can just add your own indexing variable(s).
int last = Model.Results.Count - 1;
int index = 0;
foreach (Item result in Model.Results)
{
//Do Things
if (index == last)
//Do Things with the last result
index++;
}
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. 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
}
}
How to convert foreach
to react to the last element:
List<int> myList = new List<int>() {1, 2, 3, 4, 5};
Console.WriteLine("foreach version");
{
foreach (var current in myList)
{
Console.WriteLine(current);
}
}
Console.WriteLine("equivalent that reacts to last element");
{
var enumerator = myList.GetEnumerator();
if (enumerator.MoveNext() == true) // Corner case: empty list.
{
while (true)
{
int current = enumerator.Current;
// Handle current element here.
Console.WriteLine(current);
bool ifLastElement = (enumerator.MoveNext() == false);
if (ifLastElement)
{
// Cleanup after last element
Console.WriteLine("[last element]");
break;
}
}
}
enumerator.Dispose();
}
Just store the previous value and work with it inside the loop. Then at the end the 'previous' value will be the last item, letting you handle it differently. No counting or special libraries required.
bool empty = true;
Item previousItem;
foreach (Item result in Model.Results)
{
if (!empty)
{
// We know this isn't the last item because it came from the previous iteration
handleRegularItem(previousItem);
}
previousItem = result;
empty = false;
}
if (!empty)
{
// We know this is the last item because the loop is finished
handleLastItem(previousItem);
}
What about little simpler approach.
Item last = null;
foreach (Item result in Model.Results)
{
// do something with each item
last = result;
}
//Here Item 'last' contains the last object that came in the last of foreach loop.
DoSomethingOnLastElement(last);