How can I create a dynamic Select on an IEnumerable at runtime?

后端 未结 3 1608
礼貌的吻别
礼貌的吻别 2020-12-14 12:37

Given that I have an IEnumerable, where T is any object, how can I select a specific property from it, given that I know the name of the o

3条回答
  •  有刺的猬
    2020-12-14 13:12

    It is possible to do this using an Expression

    e.g.

    private class Foo {
        public string Bar { get; set; }
    }
    
    private IEnumerable SomeFoos = new List() {
        new Foo{Bar = "Jan"},
        new Foo{Bar = "Feb"},
        new Foo{Bar = "Mar"},
        new Foo{Bar = "Apr"},
    };
    
    [TestMethod]
    public void GetDynamicProperty() {
    
            var expr = SelectExpression("Bar");
            var propValues = SomeFoos.Select(expr);
    
            Assert.IsTrue(new[] { "Jan", "Feb", "Mar", "Apr" }.SequenceEqual(propValues));
    
        }
    
    public static Func SelectExpression(string fieldName) {
    
        var param = Expression.Parameter(typeof(TItem), "item");
        var field = Expression.Property(param, fieldName);
        return Expression.Lambda>(field, new ParameterExpression[] { param }).Compile();
    
    }
    

    hth,
    Alan.

提交回复
热议问题