Zed-K
Zed-K

Reputation: 999

C# - Iterate through given type elements inside a List<T>

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!

Upvotes: 3

Views: 1081

Answers (1)

George Polevoy
George Polevoy

Reputation: 7681

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
;

Upvotes: 13

Related Questions