How do I iterate a .Net IList collection in the reverse order?
-
01-07-2019 - |
Question
I have an IList that contains items ( parent first ), they need to be added to a Diagram Document in the reverse order so that the parent is added last, drawn on top so that it is the first thing to be selected by the user.
What's the best way to do it? Something better/more elegant than what I am doing currently which I post below..
Solution
If you have .NET 3.5 you could use LINQ's Reverse?
foreach(var item in obEvtArgs.NewItems.Reverse())
{
...
}
(Assuming you're talking about the generic IList)
OTHER TIPS
Based on the comments to Davy's answer, and Gishu's original answer, you could cast your weakly-typed System.Collections.IList
to a generic collection using the System.Linq.Enumerable.Cast
extension method:
var reversedCollection = obEvtArgs.NewItems
.Cast<IMySpecificObject>( )
.Reverse( );
This removes the noise of both the reverse for
loop, and the as
cast to get a strongly-typed object from the original collection.
NewItems is my List here... This is a bit clunky though.
for(int iLooper = obEvtArgs.NewItems.Count-1; iLooper >= 0; iLooper--)
{
GoViewBoy.Document.Add(CreateNodeFor(obEvtArgs.NewItems[iLooper] as IMySpecificObject, obNextPos));
}
You don't need LINQ:
var reversed = new List<T>(original); // assuming original has type IList<T>
reversed.Reverse();
foreach (T e in reversed) {
...
}