It’s great. It’s so beautiful. I really like it.

Reflecting types using LINQ.

How can we do it?

We can use Reflection of course, but with LINQ it shortest and simplest.

Declare “Type” object , assign the class you want to query and query with LINQ.

Example 1:

To get all methods of a class:

   1:  Type tPerson = typeof(Person);
   2:  var methods = from method in tPerson.GetMethods()
   3:                select method;
   4:   
   5:  Console.WriteLine("All methods:");
   6:  foreach (var m in methods)
   7:  {
   8:      Console.WriteLine(m.Name);
   9:  }

 

Example 2:

To get all methods that returns “int”, use the “where’ clause:

   1:  var ints = from method in tPerson.GetMethods()
   2:                where method.ReturnType == typeof(int)
   3:                select method;
   4:   
   5:  Console.WriteLine("All methods that returns int:");
   6:  foreach (var intType in ints)
   7:  {
   8:      Console.WriteLine(intType.Name);
   9:  }

Similar Posts:

Tags: , ,



2 Comments to “Query types using LINQ”

  1. Maor David-Pur | June 22nd, 2009 at 23:15

    This comment originally written by:
    It's great. It's so beautiful. I really like it. Reflecting types using LINQ. How can we do it? We can use Reflection of course, but with LINQ it shortest and simplest. Declare "Type" object , assign the class you want to query and query

  2. Maor David-Pur | June 22nd, 2009 at 23:15

    This comment originally written by:Yordan Georgiev

    Cool,

    I was searching 2 days ago 1 hour for such an elegant and working code snippet … to improve a debugging method of mine (in ysgitdiary.blogspot.com/…/effective-debugging-in-aspnet.html)

    Thanks !!!

Leave a Comment