views:

1796

answers:

3

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

A: 

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));
            }
Gishu
why not include this in the question? Why post as an answer?
spoon16
From the FAQ: Can I answer my own question? What if it's not really a question?It's best to actually submit an answer, rather than just answering in the question itself. This allows the answer to be voted on and evaluated fairly against other people's answers.
digiguru
+4  A: 

If you have .NET 3.5 you could use LINQ's Reverse?

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

(Assuming your talking about the generic IList)

Davy Landman
I was about to give up because I couldn't find the System.Linq namespace in intellisense. I'm working with NotifyCollectionChangedEventArgs which uses a System.Collections.IList.. so I can't Reverse() anyways..thx. voted up.
Gishu
you could always use a (new List<Object>(obEvtArgs.NewItems)).Reverse(), but you'll get higher memory usage and lesser performance.
Davy Landman
:) For loops are more familiar and readable to me atleast. Need to get acquainted with LINQ one of these days...
Gishu
+1  A: 

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.

Emperor XLII