How to iterate a .Net IList collection in reverse order?

I have an IList that contains elements (first parent), they need to be added to the chart document in the reverse order, so that the parent is added last, drawn on top, so this is the first thing the user needs to select.

What is the best way to do this? Something better / more elegant than what I am doing now which I post below ..

+5
source share
4 answers

If you have .NET 3.5, can you use LINQ Reverse?

foreach(var item in obEvtArgs.NewItems.Reverse())
{
   ...
}

(Assuming you're talking about a generic IList)

+7
source

Davy answer, , - System.Collections.IList , System.Linq.Enumerable.Cast:

var reversedCollection = obEvtArgs.NewItems
  .Cast<IMySpecificObject>( )
  .Reverse( );

for, as .

+2

NewItems is my list here ... It's a bit awkward.

for(int iLooper = obEvtArgs.NewItems.Count-1; iLooper >= 0; iLooper--)
            {
                GoViewBoy.Document.Add(CreateNodeFor(obEvtArgs.NewItems[iLooper] as IMySpecificObject, obNextPos));
            }
0
source

You do not need LINQ:

var reversed = new List<T>(original); // assuming original has type IList<T>
reversed.Reverse();
foreach (T e in reversed) {
  ...
}
0
source

All Articles