Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I iterate a .Net IList collection in the reverse order?

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..

like image 527
Gishu Avatar asked Sep 18 '08 08:09

Gishu


2 Answers

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)

like image 82
Davy Landman Avatar answered Nov 06 '22 10:11

Davy Landman


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.

like image 31
Emperor XLII Avatar answered Nov 06 '22 08:11

Emperor XLII