Search code examples
c#.netdata-annotations

How to get a List of DataAnnotation Display Name


I have a class with Data Annotations and need to get a list of strings from Display and attribute Name.

I already try some approaches. In method GetAttributesNames().

internal class TVSystemViewData : BaseViewData
        {
            [Display(Name = "BoxType", Description = "")]
            public String BoxType { get; set; }

            [Display(Name = "BoxVendor", Description = "")]
            public String BoxVendor { get; set; }

            [Display(Name = "ClientId", Description = "")]
            public String ClientId { get; set; }

            [Display(Name = "HostName", Description = "")]
            public String HostName { get; set; }

            [Display(Name = "OSVersion", Description = "")]
            public String OSVersion { get; set; }
            [Display(Name = "SerialNumber", Description = "")]
            public String SerialNumber { get; set; }


            internal void GetAttributesNames()
            {
                var listOfFieldNames = typeof(TVSystemViewData)
                .GetProperties()
                .Select(x =>  x.GetCustomAttributes(typeof(DisplayAttribute), true))
                .Where(x => x != null)
                .ToList();

            }
}

Solution

  • this might help

    internal List<string> GetAttributesNames()  //changed type returned
        {
            return  typeof(TVSystemViewData)
              .GetProperties()                //so far like you did
              .SelectMany(x=>x.GetCustomAttributes(typeof(DisplayAttribute),true) //select many because can have multiple attributes
              .Select(e=>((DisplayAttribute)e))) //change type from generic attribute to DisplayAttribute
              .Where(x => x != null).Select( x => x.Name) //select not null and take only name
              .ToList(); // you know ;)
        }
    

    Hope this helps