"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can LINQ Efficiently Find All Derived Types of a Specified Base Type?

How Can LINQ Efficiently Find All Derived Types of a Specified Base Type?

Posted on 2025-03-23
Browse:277

How Can LINQ Efficiently Find All Derived Types of a Specified Base Type?

Finding Derived Types of a Specified Type

In programming, it is often necessary to determine all derived types of a given base type. Traditionally, this has been achieved through laborious techniques such as iterating over all types in loaded assemblies and manually checking for assignability to the target type.

However, a more efficient and elegant solution exists using LINQ (Language Integrated Query). The following code snippet provides a straightforward and performant way to accomplish this task:

var listOfDerivedTypes = (
                from domainAssembly in AppDomain.CurrentDomain.GetAssemblies()
                from type in domainAssembly.GetTypes()
                where typeof(BaseTypeName).IsAssignableFrom(type)
                select type).ToArray();

Alternative Fluent Syntax:

The LINQ expression can also be written in a more fluent style for enhanced readability:

var listOfDerivedTypes = AppDomain.CurrentDomain.GetAssemblies()
                .SelectMany(domainAssembly => domainAssembly.GetTypes())
                .Where(type => typeof(BaseTypeName).IsAssignableFrom(type))
                .ToArray();

Customizations:

  • Only Publicly Visible Types: To retrieve only types that are publicly visible, use domainAssembly.GetExportedTypes() instead of domainAssembly.GetTypes().
  • Exclude Original Base Class: To prevent the original base type from being included in the results, add && type != typeof(BaseTypeName) to the where clause.
  • Exclude Abstract Classes: To exclude abstract classes, add && ! type.IsAbstract to the where clause.
  • Generic Types: Handling generic types requires additional considerations. For guidance, refer to the linked resources in the "Details" section.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3