IHeartsCoding
IHeartsCoding

Reputation:

Sorting a list with null values

I have been working with lists in C# and I was wondering how to go about easily sorting a list that doesn't always have values for specific fields.

If, for instance, there was a list of people and each of them had a DateOfBirth and I wanted to sort all of the people, even those without that specific field, but I would want those to be seperated from the original group (those with DOB).

I know that this could probably be done with LINQ but I am not really sure how to approach it.

Any help would be greatly appreciated!

Upvotes: 18

Views: 10200

Answers (1)

Rion Williams
Rion Williams

Reputation: 76547

I believe something like this will accomplish what you are looking for (using LINQ), or perhaps point you in the right direction:

var sortedList = listOfPeople
                 .OrderBy(p => p.DateOfBirth.HasValue)
                 .ThenBy(p => p.DateOfBirth);

If you are looking for additional information on the same topic, you might want to check out the following article : Sorting Lists with Null Values - Deborah Kurata

Upvotes: 18

Related Questions