I’m building a method to get the DisplayAttribute from System.ComponentModel.DataAnnotations to show on a label for the property.
[Display(Name="First Name")]
public string FirstName { get; set; }
The method is working well:
string GetDisplay(Type dataType, string property)
{
PropertyInfo propInfo = dataType.GetProperty(property);
DisplayAttribute attr = propInfo.GetCustomAttributes(false).OfType<DisplayAttribute>().FirstOrDefault();
return (attr == null) ? propInfo.Name : attr.Name;
}
The call of method can be:
lblNome.Text = GetDisplay(typeof(Person), "FirstName") + ":";
I can use a more elegant sintax using Generics, like:
string GetDisplay<T>(string property)
{
PropertyInfo propInfo = typeof(T).GetProperty(property);
DisplayAttribute attr = propInfo.GetCustomAttributes(false).OfType<DisplayAttribute>().FirstOrDefault();
return (attr == null) ? propInfo.Name : attr.Name;
}
And the call:
GetDisplay<Person>("FirstName");
So, I would like to make it more more elegant using lambda expressions turning the call like this:
GetDisplay<Person>(p => p.FirstName);
The question is how can I achieve this?
Here is the method I use to fetch property name given by lambda expression:
Using this method you can just call the previous method: