Reputation: 7806
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace Test_console_application
{
class Program
{
static void Main(string[] args)
{
var parentPropertyName = "Measurements";
var parentPropertyType = typeof (Measurement);
var propertyName = "Data";
var parameterExp = Expression.Parameter(typeof(Inverter), "type");
var propertyExp = Expression.Property(parameterExp, parentPropertyName);
var method = typeof(Enumerable).GetMethods(BindingFlags.Static | BindingFlags.Public)
.Single(x => x.ToString() == "Double Min[TSource](System.Collections.Generic.IEnumerable`1[TSource], System.Func`2[TSource,System.Double])")
.MakeGenericMethod(parentPropertyType);
var minParameterExp = Expression.Parameter(parentPropertyType, "type2");
var minPropertyExp = Expression.Property(minParameterExp, propertyName);
var minMethodExp = Expression.Call(method, propertyExp, minPropertyExp);
}
}
public class Inverter
{
public IList<Measurement> Measurements { get; set; }
}
public class Measurement
{
public double Data { get; set; }
}
}
When I run this code I get a ArgumentException:
Expression of type 'System.Double' cannot be used for parameter of type 'System.Func
2[Test_console_application.Measurement,System.Double]' of method 'Double Min[Measurement](System.Collections.Generic.IEnumerable
1[Test_console_application.Measurement], System.Func`2[Test_console_application.Measurement,System.Double])'
I understands what it says, but I just thought that I was what I was doing that with minPropertyExp.
I can't figure out what I need to change - any clue?
Upvotes: 1
Views: 626
Reputation: 64648
You should not pass a property expression as Func. You should pass a method.
You did something like:
Measurements.Min(type2.Data)
Instead of
Measurements.Min(x => x.Data)
From the comment by the Morten Holmgaard
var minMethod = Expression.Lambda(minPropertyExp, minParameterExp);
var minMethodExp = Expression.Call(method, propertyExp, minMethod);
Upvotes: 1