how do I check if an entity is the first element of a foreach loop
There are several ways that you could do that.
- Use a
for
loop instead - Set a Boolean flag
- Use Linq to get the
list.First()
and thenforeach
overlist.Skip(1)
I like the Linq way, but without the Skip(1), this way you can also use it for the last item in a list and your code remains clean imho :)
foreach(var item in items)
{
if (items.First()==item)
item.firstStuff();
else if (items.Last() == item)
item.lastStuff();
item.otherStuff();
}