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
List<int> ListInt = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int count = ListInt.Count;
int index = 1;
foreach (var item in ListInt)
{
if (index != count)
{
Console.WriteLine("do something at index number " + index);
}
else
{
Console.WriteLine("Foreach loop, this is the last iteration of the loop " + index);
}
index++;
}
//OR
int count = ListInt.Count;
int index = 1;
foreach (var item in ListInt)
{
if (index < count)
{
Console.WriteLine("do something at index number " + index);
}
else
{
Console.WriteLine("Foreach loop, this is the last iteration of the loop " + index);
}
index++;
}
You can make an extension method specially dedicated to this:
public static class EnumerableExtensions {
public static bool IsLast<T>(this List<T> items, T item)
{
if (items.Count == 0)
return false;
T last = items[items.Count - 1];
return item.Equals(last);
}
}
and you can use it like this:
foreach (Item result in Model.Results)
{
if(Model.Results.IsLast(result))
{
//do something in the code
}
}
".Last()" didnt work for me, so I had to do something like this:
Dictionary<string, string> iterativeDictionary = someOtherDictionary;
var index = 0;
iterativeDictionary.ForEach(kvp =>
index++ == iterativeDictionary.Count ?
/*it's the last item */ :
/*it's not the last item */
);
To do something additional to each element except for the last one, function based approach can be used.
delegate void DInner ();
....
Dinner inner=delegate
{
inner=delegate
{
// do something additional
}
}
foreach (DataGridViewRow dgr in product_list.Rows)
{
inner()
//do something
}
}
This approach has apparent drawbacks: less code clarity for more complex cases. Calling delegates might be not very effective. Troubleshooting might be not quite easy. The bright side - coding is fun!
Having said that, I would suggest using plain for loops in trivial cases, if you know that your collection's count is not terribly slow.
We can check last item in loop.
foreach (Item result in Model.Results)
{
if (result==Model.Results.Last())
{
// do something different with the last item
}
}
The best approach would probably be just to execute that step after the loop: e.g.
foreach(Item result in Model.Results)
{
//loop logic
}
//Post execution logic
Or if you need to do something to the last result
foreach(Item result in Model.Results)
{
//loop logic
}
Item lastItem = Model.Results[Model.Results.Count - 1];
//Execute logic on lastItem here