Performance Stub: getting all subtype items from a list

Performance Stubs These blog posts are simply times I wanted to identify the fastest method for accomplishing a particular goal. As I write the code, I like to make some light notes of alternatives while driving forward with the first implementation that makes it from my brain to my fingers. When I get the chance, I can go back and flesh out the two versions and drop them into some basic Stopwatch timing to determine which is better in terms of raw speed. Factoring those results with clarity of code, I have a method I will likely choose the next time I need the same feature. Goal Given a particular IEnumerable, find all the elements that are of a particular type (subclass, in this case). Method 1: Select As, Where Not Null The as operator with convert between two types with one nice tweak. If the cast cannot happen, it results in null. In this version, we massage the list by hitting all items with an as cast and then filter out the ones that didn’t cast successfully. public static IEnumerable<SubSomething> SelectAsWhereNotNull(IEnumerable<Something> source) { return source.Select(item => item as SubSomething).Where(item => item != null); } Method 2: Where Is, Cast… Continue reading