0

I'm new at Reflection and I was trying the below peice of code

var queryableLastMethodInfo = typeof(Queryable).GetMethod("Last", new Type[]{ typeof(IQueryable<>) });

but queryableLastMethodInfo always returns null.

Could you please help?

Damian
  • 2,752
  • 1
  • 29
  • 28
Shousha
  • 43
  • 2
  • 10

3 Answers3

3

This should give you the MethodInfo of the "Last" extension method that doesn't take a predicate:

var queryableLastMethodInfo = typeof(Queryable).GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
    .FirstOrDefault(x => x.Name == "Last" && x.GetParameters().Count() == 1);

...and this should give you the other one:

var queryableLastMethodInfo = typeof(Queryable).GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
    .FirstOrDefault(x => x.Name == "Last" && x.GetParameters().Count() == 2);
mm8
  • 163,881
  • 10
  • 57
  • 88
1

You can find all Last methods and select the one with only one parameter:

var method = typeof (Queryable).GetMethods()
                               .Where(m => m.Name == "Last")
                               .First(m => m.GetParameters().Length == 1);

Generic case is described in this question and answer.

Community
  • 1
  • 1
Damian
  • 2,752
  • 1
  • 29
  • 28
0

Don't take risk code failed if Queryable receuve new methods called "Last" and taking only one parameter.

Accurate is never to much.

var queryableLastMethodInfo = typeof(Queryable).GetMethods().Single(_Method => _Method.Name == "Last" && _Method.IsGenericMethod && _Method.GetGenericArguments().Length == 1 && _Method.GetParameters().Length == 1   && _Method.GetParameters().Single().ParameterType == typeof(IQueryable<>).MakeGenericType(_Method.GetGenericArguments().Single()));
Tony THONG
  • 772
  • 5
  • 11