Reputation: 419
foreach(var item in myObservalbleCollection)
{
//samoe coding
}
Above code will loop the items in the observable class from the beginning. I want to loop the this object from the last Item
ex 9,8,7,6,5,4,3,2,1,0 instead of 1,2,3,4,5,6,7,8,9... Please give me a solution to do this in c#
Upvotes: 0
Views: 2496
Reputation: 106826
Instead of using foreach
you can use a for
loop running from the end of the collection and to the start:
for (var i = myObservableCollection.Count - 1; i >= 0; i -= 1) {
var item = myObservableCollection[i];
// Process item
}
This is possible because ObservableCollection<T>
implement IList<T>
which provides both the count of the elements in the collection and indexed access to these elements in addition to the forward teration provided by IEnumerable<T>
used by foreach
. This is the most efficient solution.
You can also use LINQ Reverse
which is available for any collection implementing IEnumerable<T>
:
foreach (var item in myObservableCollection.Reverse()) {
// Process item
}
This will actually copy all the elements in the collection to a new array before iterating them in reverse order. While less efficient than the first solution it should not matter in most cases.
Upvotes: 3
Reputation: 222582
You could reverse
the observablecollection and do the loop
var myObservalbleCollection = new ObservableCollection<YourType>(collection.Reverse());
foreach(var item in myObservalbleCollection)
{
//some coding
}
Upvotes: 2