Given that I have an IEnumerable<T>
, where T
is any object, how can I select a specific property from it, given that I know the name of the one of the property names at run time as a string?
For example:
var externalIEnumerable = DataPassedFromConsumingCode(); // `IEnumerable<T>`
string knownPropertyName = "Foo";
var fooSelect = externalIEnumerable.Select(...);
In essence, I'm obviously just doing externalIEnumerable.Select(x=> x.Foo);
, but I need to perform this Select
at runtime, when I don't have control over when it's initially created.
--
ANSWER: Based on AlanT's answer, here's what I actually did:
public Expression<Func<TItem, object>> SelectExpression<TItem>(string fieldName)
{
var param = Expression.Parameter(typeof(TItem), "item");
var field = Expression.Property(param, fieldName);
return Expression.Lambda<Func<TItem, object>>(field,
new ParameterExpression[] { param });
}
I kept it as an Expression, because calling Compile
caused the IQueryable to be Enumerated, which meant the database was hit unnecessarily. So, to use it, I just do the following:
string primaryKey = _map.GetPrimaryKeys(typeof(TOriginator)).Single();
var primaryKeyExpression = SelectExpression<TOriginator>(primaryKey);
var primaryKeyResults = query.Select(primaryKeyExpression).ToList();
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…