I've got code to get DisplayNameAttribute from PropertyInfo and return it as a Pair
{Propertyname = "", DisplayName = ""}
public static IEnumerable GetDisplayNames<T>() => typeof(T).GetProperties()
.Where(p => p.IsDefined(typeof(DisplayNameAttribute), false))
.Select(p => new
{
PropertyName = p.Name,
DisplayName = p.GetCustomAttributes(typeof(DisplayNameAttribute),
false).Cast<DisplayNameAttribute>().Single().DisplayName
});
It would be fine, but I guess I don't understand anonymous types too well and I was wondering how to return value for specific item (if it is even possible - though it has to).
I thought it works like Dictionary<Tkey, TValue>, but now I know it is not. To simplify question:
How can I iterate through such construction?
CodePudding user response:
If you want to get an enumeration with tuples of property and display names, then ...
... use tuples:
public static IEnumerable<(string propertyName, string displayName)> GetDisplayNames<T>()
=> typeof(T).GetProperties()
.Where(p => p.IsDefined(typeof(DisplayNameAttribute), false))
.Select(p =>
(
propertyName: p.Name,
displayName: p.GetCustomAttributes(typeof(DisplayNameAttribute), false)
.Cast<DisplayNameAttribute>().Single().DisplayName
)
);
CodePudding user response:
Or could it be your are looking for a dictionary like:
public static Dictionary<string, string> GetDisplayNames<T>() =>
typeof(T).GetProperties()
.Where(p => p.IsDefined(typeof(DisplayNameAttribute), false))
.ToDictionary(
p => p.Name, // Key
p.GetCustomAttributes(typeof(DisplayNameAttribute), false)
.Cast<DisplayNameAttribute>()
[0] // Linq not really required
.DisplayName); // Value
CodePudding user response:
Use
IEnumerable<Dynamic>
type return type.
and to access it later: (lets say return value is dnm)
forEach(var item in dnm){
Console.WriteLine(item.PropertyName);
Console.WriteLine(item.DisplayName);
}