user441521
user441521

Reputation: 6998

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

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);

Upvotes: 2

Views: 4420

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500525

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.

Upvotes: 13

Related Questions