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

What Linq expression would I use to select the 1st overloaded method that takes a single string parameter?

For example, to return DateTime.ToString (string format) instead of DateTime.ToString (provider IFormatProvider).

t = typeof(DateTime);
string[] validMethods = { "ToString" };
return t.GetMethods().Where(a => validMethods.Contains(a.Name) & a.GetParameters().Length == 1).ToArray();
+3
source share
3 answers

You can check the list of all parameters with a call SequenceEqual:

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();
+9
source

Something like that:

var match = (from method in type.GetMethods()
             where validMethods.Contains(method.Name)
             let parameters = method.GetParameters()
             where parameters.Length == 1
             where parameters[0].ParameterType == typeof(string)
             select method).FirstOrDefault();

if (match != null)
{
    ...
}

, , , . , , , ...

+3

, , , ...

LINQ, (, , LINQ).

.

     var t = typeof(DateTime);
     string[] validMethods = { "ToString" };
     var parameters = new[] { typeof(string) };

     return t.GetMethods()
             .Where
             (
                a => validMethods.Contains(a.Name)
                     && 
                     a.GetParameters()
                      .Select(p => p.ParameterType)
                      .SequenceEqual(parameters)
             )
             .ToArray();

- .

0

Source: https://habr.com/ru/post/1730458/


All Articles