I know this is an old thread, but here is another way to do it. The advantage of this is that it is significantly faster if you need to do this in a loop. I converted the result from "func" to an object to make it more general.
var p = Expression.Parameter(typeof(string)); var prop = Expression.Property(p, "Length"); var con = Expression.Convert(prop, typeof(object)); var exp = Expression.Lambda(con, p); var func = (Func<string, object>)exp.Compile(); var obj = "ABC"; int len = (int)func(obj);
In the original question, the code was used inside linq, so the speed may be good. One could use "func" directly in the where clause if it was built correctly, for example
class ABC { public string Name { get; set; } } var p = Expression.Parameter(typeof(ABC)); var prop = Expression.Property(p, "Name"); var body = Expression.Equal(prop, Expression.Constant("Bob")); var exp = Expression.Lambda(body, p); var func = (Func<ABC, bool>)exp.Compile(); ABC[] items = "Fred,Bob,Mary,Jane,Bob".Split(',').Select(s => new ABC() { Name = s }).ToArray(); ABC[] bobs = items.Where(func).ToArray();
source share