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
Another way, which I didn't see posted, is to use a Queue. It's analogous to a way to implement a SkipLast() method without iterating more than necessary. This way will also allow you to do this on any number of last items.
public static void ForEachAndKnowIfLast<T>(
this IEnumerable<T> source,
Action<T, bool> a,
int numLastItems = 1)
{
int bufferMax = numLastItems + 1;
var buffer = new Queue<T>(bufferMax);
foreach (T x in source)
{
buffer.Enqueue(x);
if (buffer.Count < bufferMax)
continue; //Until the buffer is full, just add to it.
a(buffer.Dequeue(), false);
}
foreach (T item in buffer)
a(item, true);
}
To call this you'd do the following:
Model.Results.ForEachAndKnowIfLast(
(result, isLast) =>
{
//your logic goes here, using isLast to do things differently for last item(s).
});
Improving Daniel Wolf answer even further you could stack on another IEnumerable
to avoid multiple iterations and lambdas such as:
var elements = new[] { "A", "B", "C" };
foreach (var e in elements.Detailed())
{
if (!e.IsLast) {
Console.WriteLine(e.Value);
} else {
Console.WriteLine("Last one: " + e.Value);
}
}
The extension method implementation:
public static class EnumerableExtensions {
public static IEnumerable<IterationElement<T>> Detailed<T>(this IEnumerable<T> source)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
using (var enumerator = source.GetEnumerator())
{
bool isFirst = true;
bool hasNext = enumerator.MoveNext();
int index = 0;
while (hasNext)
{
T current = enumerator.Current;
hasNext = enumerator.MoveNext();
yield return new IterationElement<T>(index, current, isFirst, !hasNext);
isFirst = false;
index++;
}
}
}
public struct IterationElement<T>
{
public int Index { get; }
public bool IsFirst { get; }
public bool IsLast { get; }
public T Value { get; }
public IterationElement(int index, T value, bool isFirst, bool isLast)
{
Index = index;
IsFirst = isFirst;
IsLast = isLast;
Value = value;
}
}
}
foreach (DataRow drow in ds.Tables[0].Rows)
{
cnt_sl1 = "<div class='col-md-6'><div class='Slider-img'>" +
"<div class='row'><img src='" + drow["images_path"].ToString() + "' alt='' />" +
"</div></div></div>";
cnt_sl2 = "<div class='col-md-6'><div class='Slider-details'>" +
"<p>" + drow["situation_details"].ToString() + "</p>" +
"</div></div>";
if (i == 0)
{
lblSituationName.Text = drow["situation"].ToString();
}
if (drow["images_position"].ToString() == "0")
{
content += "<div class='item'>" + cnt_sl1 + cnt_sl2 + "</div>";
cnt_sl1 = "";
cnt_sl2 = "";
}
else if (drow["images_position"].ToString() == "1")
{
content += "<div class='item'>" + cnt_sl2 + cnt_sl1 + "</div>";
cnt_sl1 = "";
cnt_sl2 = "";
}
i++;
}
You can do like this :
foreach (DataGridViewRow dgr in product_list.Rows)
{
if (dgr.Index == dgr.DataGridView.RowCount - 1)
{
//do something
}
}
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
}