0

I want to invoke IEnumerable<T>.Any() via MethodInfo.

    List<int> list = new List<int>();
    for (int i = 0; i < 10; i++)
    {
        list.Add(i);
    }

    Func<C, bool> func = c => c.Value > 10;
    Expression<Func<int, bool>> exp = (Expression<Func<int, bool>>)(c => c > 10);
    MethodInfo[] mis = typeof(System.Linq.Enumerable).GetMethods();
    MethodInfo miAny = mis.FirstOrDefault(d => d.Name == "Any" && d.GetParameters().Count()==2);
    var gf = miAny.MakeGenericMethod(new Type[] {list.GetType() });
    var re = gf.Invoke(null, new object[] {list,func });

But compiler report error at var re = gf.Invoke(null, new object[] {list,func });, say

`can't convert “System.Collections.Generic.List`1[System.Int32]” to “System.Collections.Generic.IEnumerable`1[System.Collections.Generic.List`1[System.Int32]]”`。

How can I repair this error?

user2155362
  • 1,657
  • 5
  • 18
  • 30
  • 2
    Your `MakeGenericMethod` is wrong. The type parameter of the generic method you want is `int`, not `List` -- think of what `Any<...>()` should return. – Jeroen Mostert Apr 09 '19 at 07:51
  • What exactly are you trying to achieve (high level overview)? Would [Dynamic LINQ](https://github.com/StefH/System.Linq.Dynamic.Core) help in that goal? – ProgrammingLlama Apr 09 '19 at 07:52
  • Didn't you already ask this question? https://stackoverflow.com/q/55586426/491907 – pinkfloydx33 Apr 09 '19 at 09:00

1 Answers1

0

This code works:

List<int> list = new List<int>();
for (int i = 0; i< 12; i++)
{
    list.Add(i);
}

MethodInfo[] mis = typeof(System.Linq.Enumerable).GetMethods();
MethodInfo miAny = mis.FirstOrDefault(d => d.Name == "Any" && d.GetParameters().Count() == 2);
Func<int, bool> func = c => c > 10;
MethodInfo gf = miAny.MakeGenericMethod(new Type[] { typeof(int) });
bool any = (bool)gf.Invoke(null, new object[] { list, func });
mm8
  • 163,881
  • 10
  • 57
  • 88