Linq access property by variable

后端 未结 5 1161
谎友^
谎友^ 2020-12-03 18:24

Let\'s say I have a class like:

public class Foo
{
    public string Title {get;set;}
}

Now, let\'s assume I have a public List

5条回答
  •  不知归路
    2020-12-03 18:47

    I know this is an old thread but here is another way to do it. This has the advantage of being significantly faster if you need to do it in a loop. I have converted the result out of "func" to be object to make it a bit more general purpose.

            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)exp.Compile();
    
            var obj = "ABC";
            int len = (int)func(obj);
    

    In the original question the code was being used inside linq so speed could be good. It would be possible to use "func" direct in the where clause also if it was built correctly, eg

            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)exp.Compile();
    
            ABC[] items = "Fred,Bob,Mary,Jane,Bob".Split(',').Select(s => new ABC() { Name = s }).ToArray();
            ABC[] bobs = items.Where(func).ToArray();
    

提交回复
热议问题