Tuesday, June 3, 2008

More Linq - Find all methods having an attribute

Not much time tonight, but here a little helper method that I wrote today. It's just another example of my Linq addiction of late.

I've had to search all loaded assemblies for methods or classes with certain custom attributes on them dozens of times when writing some generic framework for something or such... So I linqified it today, and came up with this:

public static List<MethodInfo>
GetMethodsWithAttribute(Type t, bool inherit)
{
return (from ass in AppDomain.CurrentDomain
.GetAssemblies()
from c in ass.GetExportedTypes()
from m in c.GetMethods()
from a in m.GetCustomAttributes(t, inherit)
select m).ToList();
}


This sample just prints out all methods with the SecurityPermission attribute. Notice my continued "abuse" of lambda as well...

GetMethodsWithAttribute(
typeof(SecurityPermissionAttribute),
true)
.ForEach((a) =>
Console.WriteLine("{0}.{1}",
a.DeclaringType.Name,
a.Name));

1 comment:

Smith said...

Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from Dot Net Training in Chennai. or learn thru ASP.NET Essential Training Online . Nowadays Dot Net has tons of job opportunities on various vertical industry.
or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.