tags:

views:

87

answers:

1

I've got an abstract class (Object2D), and several class that inherits Object2D (DisplayObject2D for instance)

I use a List to store all references to these objects.

I'd like to iterate through every DisplayObject2D in this List.

So far, the following code is working, but being new to C# development, I wanted to know if there wasn't any better practice to do so :

List<Object2D> tmp = objects.FindAll( delegate( Object2D obj )
                                      { return obj is DisplayObject2D; } );
foreach( DisplayObject2D obj in tmp )
{
   ...
}

Thanks in advance!

+12  A: 
var objects2d = objects.OfType<DisplayObject2D>();

if you want an IEnumerable

var listOfObjects2d = objects2d.ToList();

if you want a List

Note that OfType will give you a more specific type

IEnumerable<DisplayObject2D>

If it's not what you expected, use Cast extension to cast it back to an enumerable of base type.

var listOfObjects2dFilteredByMoreSpecificType = 
 objects.OfType<DisplayObject2D>.Cast<Object2D>()
//.ToList() // until you really need an IList<T> better leave it just an enumerable
;
George Polevoy
@George +1, thanks; your answer cleared up a spot of trouble I was in using 'OfType ... I was omitting the empty parens at the end.
BillW
Actually, "objects" is a List<Object2D>, and it seems that this OfType method doesn't exist (it doesn't appear in the autocompletion window) =/I've been looking for "OfType" in MSDN, but I didn't really understood how to use it.
Zed-K
To use it, you have to declare using System.Linq namespace and a reference to System.Core dll.
George Polevoy
Now it works just fine, and it's really easy to use ! Thanks a lot for your help ! =)
Zed-K