Reputation: 5271
I want to order a collection with a property which is null but if not using a property that is integer.
repeaterEmployees.DataSource = employees.Distinct(new EmployeeComparer())
.OrderBy(x => x.Status ?? x.Status.ID);
repeaterEmployees.DataBind();
Employees is a class extending the List`Employee. And Employee has a property Status which is from a class Status
I got a message in the OrderBy method "Operator ?? cannot be applied to operands of type Status and int"
Upvotes: 2
Views: 5129
Reputation: 27861
You can use -1
(or any other value that you know is outside the range of valid ID values) if Status
is null
like this:
repeaterEmployees.DataSource =
employees.Distinct(new EmployeeComparer())
.OrderBy(x => x.Status == null ? -1 : x.Status.ID );
Upvotes: 9
Reputation: 20995
If this is coming from a SQL DB you should be fine, null references won't happen if calling into the database. If you just call order by, by default nulls will go to the top.
repeaterEmployees.DataSource = employees.Distinct(new EmployeeComparer())
.OrderBy(x => x.Status.ID);
repeaterEmployees.DataBind();
If your calling from linq to objects you'll have to check for null
repeaterEmployees.DataSource = employees.Distinct(new EmployeeComparer())
.OrderBy(x => x.Status == null ? -1 : x.Status.ID);
Upvotes: 0