3

I'm trying to get a dictionary containing the Property and the DisplayName of all properties in a class that have the Required Attribute.

I'm trying to work off of this extension method that I have but PropertyDescriptor does not contain a definition for Required. Any direction would be appreciated

    public static Dictionary<string, string> GetDisplayNameList<T>()
    {
        var info = TypeDescriptor.GetProperties(typeof(T))
            .Cast<PropertyDescriptor>()
            .ToDictionary(p => p.Name, p => p.DisplayName);
        return info;
    }
Tim
  • 1,249
  • 5
  • 28
  • 54

2 Answers2

4

Sure, you just need to check that the property has the Required attribute defined on it. You can access this via .Attributes. For example:

public static Dictionary<string, string> GetDisplayNameList<T>()
{
    var info = TypeDescriptor.GetProperties(typeof(T))
        .Cast<PropertyDescriptor>()
        .Where(p => p.Attributes.Cast<Attribute>().Any(a => a.GetType() == typeof(RequiredAttribute)))
        .ToDictionary(p => p.Name, p => p.DisplayName);
    return info;
}
Rob
  • 26,989
  • 16
  • 82
  • 98
  • 1
    Thanks Rob. That's exactly what I needed. – Tim Mar 24 '17 at 03:28
  • 1
    Personally I find [`.Where(p => p.GetCustomAttribute() != null)`](https://msdn.microsoft.com/en-us/library/hh194292(v=vs.110).aspx) a lot cleaner. – Scott Chamberlain Mar 24 '17 at 03:49
  • @ScottChamberlain I usually do use that, however this is on `PropertyDescriptor` rather than `PropertyInfo`, unfortunately – Rob Mar 24 '17 at 04:07
0

Does this not work?

public static Dictionary<string, string> GetNameToDisplayNameDictionary(List<T>() list) =>
   typeof(T)
      .GetProperties()
      .Where(p => p.GetAttribute<RequiredAttribute>() != null)
      .ToDictionary(p => p.Name, p => p.GetAttribute<DisplayName>().Name);

I'm guessing a little here about the DisplayName as I'm away from my computer...

ErikE
  • 48,881
  • 23
  • 151
  • 196