I’ve found this example which returns custom type Car objects in reverse order.
Can someone explain me this code. thanks
public IEnumerable GetTheCars(bool returnReversed)
{
if(returnReversed)
{
for(int i=cars.Length; i!=0; i--)
{
yield return cars[i-1]; //this line makes me confused
}
}
else {...}
}
You indicated in your comments that you need an explanation of how the reverse ordering works.
Let’s say you have 4 cars in your list.
Your
forloop starts at a value ofcars.Length, which will be 4. For each iteration it decrements by 1. It will continue doing this while thei!=0condition is met. So, the loop will iterate with the following values ofi: 4, 3, 2, 1.If
iis used as the element index for your array/list, then you will receive cars[4], cars[3], cars[2], cars[1] (reverse order!). But because arrays in C# start at 0 (and not 1), you need to subtract 1 when accessing the elements:cars[i-1].