Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# reflection loop through methods and give unique names only (ignoring overloaded)

Tags:

c#

reflection

I'm using the following to loop through all static methods in a class but there are a number of overloaded methods. I only want unique names so for example if there are 3 overloaded methods named "Run()", then I only want 1 returned in my query and not 3. For now I don't care that there are overloaded methods. Is there a way I can filter this on the query instead of after? The class has like 600+ static methods (it's a binding from another library from a DLL) and if I can limit the unique names up front it should help make my load faster. I'm basically taking the names and populating a menu with the names.

MethodInfo[] leMethods = typeof(MyType).GetMethods(BindingFlags.Public | BindingFlags.Static);

like image 972
user441521 Avatar asked Dec 08 '25 10:12

user441521


1 Answers

I don't believe there's any way of doing it in the GetMethods call but it's easy to do afterwards with LINQ:

var methodNames = typeof(MyType).GetMethods(BindingFlags.Public |
                                            BindingFlags.Static)
                                .Select(x => x.Name)
                                .Distinct()
                                .OrderBy(x => x);

Note that I've put the ordering at the very end, so there's less to sort - and because we're only getting the name anyway, we're just performing the natural ordering.

like image 145
Jon Skeet Avatar answered Dec 09 '25 23:12

Jon Skeet