开发者

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

开发者 https://www.devze.com 2022-12-15 17:21 出处:网络
I\'ve got an abstract class (Object2D), and several class that inherits Object2D (DisplayObject2D for instance)

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 be开发者_StackOverflow中文版tter practice to do so :

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

Thanks in advance!


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
;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号