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

后端 未结 3 1609
礼貌的吻别
礼貌的吻别 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:10

    The dynamic linq library allows you to specify predicates and projections on the fly and may fit your use case-

    http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

    0 讨论(0)
  • 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<Foo> SomeFoos = new List<Foo>() {
        new Foo{Bar = "Jan"},
        new Foo{Bar = "Feb"},
        new Foo{Bar = "Mar"},
        new Foo{Bar = "Apr"},
    };
    
    [TestMethod]
    public void GetDynamicProperty() {
    
            var expr = SelectExpression<Foo, string>("Bar");
            var propValues = SomeFoos.Select(expr);
    
            Assert.IsTrue(new[] { "Jan", "Feb", "Mar", "Apr" }.SequenceEqual(propValues));
    
        }
    
    public static Func<TItem, TField> SelectExpression<TItem, TField>(string fieldName) {
    
        var param = Expression.Parameter(typeof(TItem), "item");
        var field = Expression.Property(param, fieldName);
        return Expression.Lambda<Func<TItem, TField>>(field, new ParameterExpression[] { param }).Compile();
    
    }
    

    hth,
    Alan.

    0 讨论(0)
  • You can dynamically build an Expression<Func<T, U>>.

    0 讨论(0)
提交回复
热议问题