Search code examples
c#linqanonymous-methods

How to get single column with LINQ in anonymous method


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.


Solution

  • This condition is incorrect, because when the property propName is missing, it crashes, rather than returning false:

    .Where(x => x.GetType().GetProperty(propName).Name == propName)
    

    If you wanted to say "the dynamic type has the property propName", a proper condition for it would look like this:

    .Where(x => x.GetType().GetProperty(propName) != null)
    

    Note that this is necessary only when some, but not all, subclasses of T have the desired property propName. If the property is present in the T itself, you could get property upfront, and do the rest of the query like this:

    var theProp = typeof(T)..GetProperty(propName);
    return base.Query<T>().AsEnumerable().Select(x => theProp.GetValue(x, null));