user3639097
user3639097

Reputation: 97

How do i loop over a List from the end?

This will loop from the first index 0 , 1 , 2 ,3.... I want to loop from the last index 51 , 50 , 49....

for (int x = 0; x < data.Count(); x++)

What i need to loop over the List backwards from the end to start.

Upvotes: 3

Views: 304

Answers (2)

Enigmativity
Enigmativity

Reputation: 117010

If you are interested in only accessing each item then you can do this:

foreach (var item in data.Reverse())
{
    /* do stuff with each item */
}

The readability of this code will, in 99.99% of all cases, outweigh the performance impact.

Upvotes: 3

Adil
Adil

Reputation: 148110

You need to start from count -1, change the condition to greater or equal to zero and use decrement -- instead of increment. Read this MSDN article for (C# Reference) for more understanding of for loop.

for (int x = data.Count()-1 ; x >=0 ; x--)

Upvotes: 10

Related Questions