Using LINQ to Reflection with Lambda Expressions in C#

I think Lambda expression are cool. Not only are cool, they are pretty powerful and can make your code a lot more readable and compact. I wrote this article here about how to simply use LINQ to Reflection to list the methods and types of an assembly. In this example I will use the same project, but modify it to use Lambda Expressions.

using System;
using System.Linq;
using System.Reflection;
using System.Linq.Expressions;
 
foreach (var odpTypes in assembly.GetTypes()
    .Where(a => a.IsPublic))
{
  Console.WriteLine("Type: {0}", odpTypes.FullName);
  foreach (var odpMethods in odpTypes.GetMethods()
      .Where(i => i.ReturnType.FullName != "System.String"))
  {                    
    Console.WriteLine(" {0}", odpMethods.ReturnType + 
            " " + odpMethods.Name);
  }
}

Lambda Expressions let me put where clauses, groupby clauses, etc… directly into my foreach statement. I can do this using the lambda operator =>, which means "goes to". The a within my first Where clause represents the odpTypes variable. Any property or method that is accessible from that variable are accessible from the a too. The same goes for the i.

If you take a look at my other article I think you will find that using doing it this way is more friendly and readable.

Download the source




Leave a Comment

Your email address will not be published.