Reputation: 97
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
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
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