Wednesday, October 10, 2007

LINQ to Reflection


var results = from assembly in AppDomain.CurrentDomain.GetAssemblies()
from module in assembly.GetLoadedModules()
from type in module.GetTypes()
from method in type.GetMethods()
where method.Name == "Execute"
select new
{
Assembly = assembly,
Module = module,
Type = type,
Method = method
};


This returns a set of anonymously typed objects that contain references to all of the types in all of the loaded assemblies that have an "Execute" method. If this were written in the traditional way, it would look like:

class MethodInfoContainer {
public MethodInfo Method;
public Type Type;
public Module Module;
public Assembly Assembly;
}

And the code that accomplishes what the single LINQ statement did...

List<MethodInfoContainer> results = new List<MethodInfoContainer>();

foreach(Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()){
foreach ( Module module in assembly.GetLoadedModules() )
{
foreach ( Type type in module.GetTypes() )
{
foreach ( MethodInfo method in type.GetMethods() )
{
if ( method.Name == "Execute" )
{
results.Add( new MethodInfoContainer()
{
Assembly = assembly,
Module = module,
Type = type,
Method = method
} );

}
}
}
}
};

No comments: