Cool LINQ Stuff – queries and Reflection

This is something pretty cool that LINQ can be used for: querying information on Reflection data. For instance, the query below creates a list of all classes that are subclasses of the Exception class within the currently loaded assemblies. It also lists the properties declared at the subclasses level, making it easier to spot the properties that haven’t been inherited from the baseclass:

var exceptionClasses =
          from assembly in AppDomain.CurrentDomain.GetAssemblies()
          from type in assembly.GetTypes()
          where type.IsSubclassOf(typeof(Exception))
          from prop in type.GetProperties(BindingFlags.Instance | 
                                            BindingFlags.Public | 
          select new { AssemblyName = assembly.GetName().Name, 
TypeName = type.Name,
PropertyName = prop.Name }; foreach (var item in exceptionClasses) { Console.WriteLine(
String.Format("assembly = {0} | type = {1} | prop = {2}", item.AssemblyName, item.TypeName, item.PropertyName)); }

The query below gets all classes that implemented IEnumerable<T>, available on the currently loaded assemblies:

var query =
          from assembly in AppDomain.CurrentDomain.GetAssemblies()
          from type in assembly.GetTypes()
          from method in type.GetMethods()
          where method.IsStatic
          && method.ReturnType.GetInterface("IEnumerable`1") != null
          orderby method.DeclaringType.Name, method.Name
          group method by new
                    Class = method.DeclaringType.Name,
                    Method = method.Name

            foreach (var item in query)
                       item.Key.Class + " - " + item.Key.Method);

 The last query I got from the following book (which is a great introduction to LINQ, by the way):

Introducing Microsoft LINQ
by Paolo Pialorsi, Marco Russo

Read more about this title…

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: