Reputation: 137
i'm trying to get data from a db, but I don't get the expected result.
var totalNews = GetNewsData(false, CmsPagesRepository.CurrentUserSettings.CmsLanguageID)
.OrderBy(n => n.Priority)
.ThenBy(n => n.Index)
.ThenBy(n => n.Title);
I have a table of News with a column Index and a column Priority, and I want to order the news by Priority and if the Priority is null first show the ones with priority and after the others.
But now if a have 3 news with index (1,4,2) and priority(null,0,1) in the list of totalNews
I get on the first position the one with Priority null and index 1. What do I have to correct?
Upvotes: 3
Views: 888
Reputation: 660533
Though the answer you have accepted will work, I don't much like it. First, in the unlikely event that you have some of the largest integer in there, they will not be ordered correctly with respect to null. A good solution works for any inputs, not just common inputs. Second, the code does not match the specification. Your specification is "order first by whether the priority is null, then by priority, then by...", so that's how the code should read. I would suggest you write:
GetNewsData(...)
.OrderBy(n => n.Priority == null) // nulls last
.ThenBy(n => n.Priority)
.ThenBy(n => n.Index)
.ThenBy(n => n.Title);
Upvotes: 9
Reputation: 1191
You probably want a simple null check in the OrderBy priority, like this:
.OrderBy(n => n.Priority ?? int.MaxValue)
This will default the priority to a high number if it is null.
Upvotes: 1