Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get properties of class by order using reflection

Please refer to this code

public class A : 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 to get all properties of class through order by orderAttribute of Display. I have tried with this code to do

 var prop = typeof(A)
            .GetProperties()
            .OrderBy(p => ((DisplayAttribute)p.GetCustomAttributes(typeof(DisplayAttribute),  true).FirstOrDefault).Order);

but it causes an error

object reference not to set an instance of object

I assumed this issue because of some property not having "Order" property in "DisplayAttribute" .

How to handle this kind of situation? I need to order all the properties even though some property not having the value of order property.

like image 279
SivaRajini Avatar asked Dec 09 '22 09:12

SivaRajini


1 Answers

You are missing brackets () on FirstOrDefault operator. Also you should deal with case when default value is returned. I suggest to select Order value before getting first or default value. That will return 0 for all properties which don't have DisplayAttribute:

var prop = typeof(A)
    .GetProperties()
    .OrderBy(p => p.GetCustomAttributes(typeof(DisplayAttribute), true)
                   .Cast<DisplayAttribute>()
                   .Select(a => a.Order)
                   .FirstOrDefault());

If you want properties without DisplayAttribute to be last, you can provide Int32.MaxValue as default value to be returned:

                   .Select(a => a.Order)
                   .DefaultIfEmpty(Int32.MaxValue)
                   .First()
like image 80
Sergey Berezovskiy Avatar answered Dec 11 '22 08:12

Sergey Berezovskiy