c# - Get properties of class by order using reflection -


please refer code

public class : b {      [display(name = "initial score code", order =3)]      public code { get; set; }       [display(name = "initial score code", order =2)]      public name{ get; set; } ............  } 

i need properties of class through order orderattribute of display. have tried code do

 var prop = typeof(a)             .getproperties()             .orderby(p => ((displayattribute)p.getcustomattributes(typeof(displayattribute),  true).firstordefault).order); 

but causes error

object reference not set instance of object

i assumed issue because of property not having "order" property in "displayattribute" .

how handle kind of situation? need order properties though property not having value of order property.

you missing brackets () on firstordefault operator. should deal case when default value returned. suggest select order value before getting first or default value. return 0 properties don't have displayattribute:

var prop = typeof(a)     .getproperties()     .orderby(p => p.getcustomattributes(typeof(displayattribute), true)                    .cast<displayattribute>()                    .select(a => a.order)                    .firstordefault()); 

if want properties without displayattribute last, can provide int32.maxvalue default value returned:

                   .select(a => a.order)                    .defaultifempty(int32.maxvalue)                    .first() 

Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -