In a foreach loop, how do I identify the first element? For example, in the snippet below, can I identify the Content item that is the first (or last) item?
@foreach(var Content in AsDynamic(Data["Default"])) { ?? }
In a foreach loop, how do I identify the first element? For example, in the snippet below, can I identify the Content item that is the first (or last) item?
@foreach(var Content in AsDynamic(Data["Default"])) { ?? }
You can do something like this:
@{int i = 1;}
@foreach(var Content in AsDynamic(Data["Default"]))
{
if(i==1)
{
//this is first element
}
i++;
}
Another option is to compare the current item to the First() or Last(). But you may run into some surprises because of the Dynamic wrapper caused by AsDynamic. So my pseudocode recommendation is a bit like this
var firstI = Data["Default"].FirstOrDefault(); // returns null if nothing
var lastI = Data["Default"].LastOrDefault(); // null...
@foreach(var Content in AsDynamic(Data["Default"]))
{
var isFirst = AsEntity(Content) == firstI; // unwrap and compare
//etc.
}