Created
March 27, 2015 01:09
-
-
Save hidori/d11b506548d5f4d4ab9c to your computer and use it in GitHub Desktop.
Get a text which specified with DisplayAttribute
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static string GetDisplayName<TModel>(Expression<Func<TModel, object>> expression) | |
{ | |
var type = typeof(TModel); | |
var propertyList = default(IEnumerable<string>); | |
switch (expression.Body.NodeType) | |
{ | |
case ExpressionType.Convert: | |
case ExpressionType.ConvertChecked: | |
var ue = expression.Body as UnaryExpression; | |
propertyList = (ue != null ? ue.Operand : null).ToString().Split(".".ToCharArray()).Skip(1); | |
break; | |
default: | |
propertyList = expression.Body.ToString().Split(".".ToCharArray()).Skip(1); | |
break; | |
} | |
var propertyName = propertyList.Last(); | |
var properties = propertyList.Take(propertyList.Count() - 1).ToArray(); | |
var expr = default(Expression); | |
foreach (string property in properties) | |
{ | |
var propertyInfo = type.GetProperty(property); | |
expr = Expression.Property(expr, type.GetProperty(property)); | |
type = propertyInfo.PropertyType; | |
} | |
var attr = (DisplayAttribute)type.GetProperty(propertyName).GetCustomAttributes(typeof(DisplayAttribute), true).SingleOrDefault(); | |
if (attr == null) | |
{ | |
MetadataTypeAttribute metadataType = (MetadataTypeAttribute)type.GetCustomAttributes(typeof(MetadataTypeAttribute), true).FirstOrDefault(); | |
if (metadataType != null) | |
{ | |
var property = metadataType.MetadataClassType.GetProperty(propertyName); | |
if (property != null) | |
{ | |
attr = (DisplayAttribute)property.GetCustomAttributes(typeof(DisplayNameAttribute), true).SingleOrDefault(); | |
} | |
} | |
} | |
return (attr != null) ? attr.Name : String.Empty; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment