0

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"])) { ?? }

Joe Craig
  • 1,244
  • 1
  • 7
  • 7

2 Answers2

0

You can do something like this:

@{int i = 1;}
@foreach(var Content in AsDynamic(Data["Default"])) 
{
    if(i==1)
    {
      //this is first element
    }
    i++;
}
0

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.
}
iJungleBoy
  • 5,325
  • 1
  • 9
  • 21