0

I am learning Expression Trees so bear with me on this one.

The idea is to call intersect an to receive the num 3.

Guess I missing something. Can you tell me what am I doing wrong here please?

    static void Main(string[] args)
    {
        List<int> arr1 = new List<int> { 1, 2, 3, 4, 5 };
        List<int> arr2 = new List<int> { 6, 7, 8, 9, 3 };

        var ex =
            Expression.Lambda<Func<List<int>>>(
                Expression.Call(
                    Expression.Constant(arr1), typeof(List<int>).GetMethod("Intersect"), Expression.Constant(arr2)));
     ....

Why is this throwing that value cannot be null?

dev hedgehog
  • 8,698
  • 3
  • 28
  • 55

1 Answers1

3

Intersect is extension method, so typeof(List<int>).GetMethod("Intersect") return null
for solve try get them from Enumerable

UPDATE

for get Intersect try this

var intersectMethod = typeof(Enumerable).GetMethods().First(a => a.Name == "Intersect" && a.GetParameters().Count() == 2).MakeGenericMethod(typeof(int));

better

var intersectMethod = typeof(Enumerable).GetMember("Intersect").First().MakeGenericMethod(typeof(int));
Grundy
  • 13,356
  • 3
  • 35
  • 55
  • Good suggestion but now I get Unhandled Exception: System.Reflection.AmbiguousMatchException: Ambiguous match found. Any ideas??? – dev hedgehog Nov 08 '13 at 08:38
  • yes, find method that you want, `public static IEnumerable Intersect(this IEnumerable first, IEnumerable second);` or `public static IEnumerable Intersect(this IEnumerable first, IEnumerable second, IEqualityComparer comparer);` and get concrete – Grundy Nov 08 '13 at 08:40
  • The first one shall match to what I wrote is my expression why is it still wrong? – dev hedgehog Nov 08 '13 at 08:41
  • it wrong because `GetMethod` in you case get only by name, and names same – Grundy Nov 08 '13 at 08:43
  • I dont get it. Could you edit your question with the correct code please? – dev hedgehog Nov 08 '13 at 08:44
  • And why is it not working the way I wrote it down? Why do I need First() and MakeGenericMethod? – dev hedgehog Nov 08 '13 at 09:21
  • You need `First()` to specify method what you want, because `Enumerable` class has several methods with same name, you need `MakeGenericMethod` to specify generic type what you want use – Grundy Nov 08 '13 at 09:29
  • I get that but is it not working with GetMethod("Intersect", new Type[] { type })? – dev hedgehog Nov 08 '13 at 09:30
  • no, for more see [GetMethod for generic method](http://stackoverflow.com/questions/4035719/getmethod-for-generic-method) – Grundy Nov 08 '13 at 10:17