Linq expression to return the first overloaded method that takes 1 string parameter

c#, linq, reflection

Solution

You can check the whole parameter list with a `SequenceEqual` call:

t = typeof(DateTime);
string[] validMethods = { "ToString" };
Type[] parameters = { typeof(string) };
return t.GetMethods()
        .Where(a => validMethods.Contains(a.Name) &&
                    a.GetParameters().Select(p => p.ParameterType)
                                     .SequenceEqual(parameters)).ToArray();

Problem

What Linq expression would I use to select the 1rst overloaded method that accepts a single string parameter? For example to return the DateTime.ToString(string format) instead of the DateTime.ToString(IFormatProvider provider). ``` t = typeof(DateTime); string[] validMethods = { "ToString" }; return t.GetMethods().Where(a => validMethods.Contains(a.Name) & a.GetParameters().Length == 1).ToArray(); ```

Original source