Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I check if an entity is the first element of a foreach loop

Tags:

c#

.net

foreach

Say I have a foreach loop.

I have to do something with the first object of the loop that I don't have to do with any of the other objects.

How do I check if the item that's currently in the loop is the first object.

like image 682
Diskdrive Avatar asked Aug 24 '10 03:08

Diskdrive


People also ask

Does foreach run in order?

forEach() , and it will definitely iterate over array elements in ascending index order (skipping indices that were never assigned a value).

What is index in foreach?

Luckily, there are several ways to get an index variable with foreach : Declare an integer variable before the loop, and then increase that one inside the loop with each loop cycle. Create a tuple that returns both the element's value and its index. Or swap the foreach loop with the for loop.

Which is correct syntax for foreach loop?

The foreach loop is mainly used for looping through the values of an array. It loops over the array, and each value for the current array element is assigned to $value, and the array pointer is advanced by one to go the next element in the array. Syntax: <?

Which is faster foreach or for?

The forloop is faster than the foreach loop if the array must only be accessed once per iteration.


1 Answers

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(); } 
like image 92
Filip Cornelissen Avatar answered Sep 23 '22 02:09

Filip Cornelissen