Home >Backend Development >C++ >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?

Linda Hamilton
Linda HamiltonOriginal
2025-01-03 19:04:41671browse

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.

The above is the detailed content of How Can LINQ Efficiently Find All Derived Types of a Specified Base Type?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn