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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With