How to get single column with anonymous method using linq expression. Here's my code and it doesn't work:
public IEnumerable<object> GetPropertyValues<T>(string propName) where T : class
{
return base.Query<T>().AsEnumerable()
.Where(x => x.GetType().GetProperty(propName).Name == propName)
.Select(x => x.GetType().GetProperty(propName).GetValue(x, null));
}
Here's the code in non generic method:
base.Query<Product>().Select(x => x.ProductName).AsEnumerable();
Thanks in advance.
This condition is incorrect, because when the property
propName
is missing, it crashes, rather than returningfalse
:If you wanted to say "the dynamic type has the property
propName
", a proper condition for it would look like this:Note that this is necessary only when some, but not all, subclasses of
T
have the desired propertypropName
. If the property is present in theT
itself, you could get property upfront, and do the rest of the query like this: