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
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...

.ForEach((a) =>

No comments: