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
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.