C # - Iterate through the given type elements inside the <T> list

I have an abstract class (Object2D) and several classes that inherit Object2D (e.g. DisplayObject2D)

I use List to store all references to these objects.

I would like to iterate over every DisplayObject2D in this list.

The following code still works, but being new to C # development, I wanted to know if there was a best practice for this:

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

Thanks in advance!

+3
source share
1 answer
var objects2d = objects.OfType<DisplayObject2D>();

if you want IEnumerable

var listOfObjects2d = objects2d.ToList();

if you want a list

Note that OfType will give you a more specific type

IEnumerable<DisplayObject2D>

If this is not what you expected, use the Cast extension to return it back to an enumerated base type.

var listOfObjects2dFilteredByMoreSpecificType = 
 objects.OfType<DisplayObject2D>.Cast<Object2D>()
//.ToList() // until you really need an IList<T> better leave it just an enumerable
;
+13

Source: https://habr.com/ru/post/1726968/


All Articles