2011-09-07 11 views
17
class SomeModel 
{ 
    [Display(Name = "Quantity Required")] 
    public int Qty { get; set; } 

    [Display(Name = "Cost per Item")] 
    public int Cost { get; set; } 
} 

Sto provando a mappare il modello in un elenco di coppie { PropertyName, DisplayName }, ma mi sono bloccato.Ottieni attributo DisplayAttribute da PropertyInfo

var properties 
    = typeof(SomeModel) 
     .GetProperties() 
     .Select(p => new 
      { 
       p.Name, 
       p.GetCustomAttributes(typeof(DisplayAttribute), 
           false).Single().ToString() 
      } 
     ); 

È possibile che questo non compila e non sono sicuro che sia il giusto approccio in ogni caso, ma si spera che si può vedere l'intento. Qualche indicazione? Grazie

risposta

25

È necessario definire diversi nomi di proprietà per il tipo anonimo.

var properties = typeof(SomeModel).GetProperties() 
    .Where(p => p.IsDefined(typeof(DisplayAttribute), false)) 
    .Select(p => new 
     { 
      PropertyName = p.Name, p.GetCustomAttributes(typeof(DisplayAttribute), 
       false).Cast<DisplayAttribute>().Single().Name 
     }); 
+0

Perfetto, grazie – fearofawhackplanet

+0

@fearofawhackplanet, Prego! –

Problemi correlati