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:
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!