OrderBy on mix of DateTime and DBNull values throws error

160 Views Asked by At

I want to order a list of my 'SortObject' class. This class is meant to imitate a DataGrid Row by holding arbitrary data organized in a dictionary (named 'Cells'), where the key is analogous to a DataGrid Column. It is enforced that any given key is associated with only one data type, for example the key "Name" will only have values of the String type.

My code (below) actually works for a majority of the cases I've used:

// public Dictionary<string, object> Cells { get; set; } <-- relevant field from 'SortObject'

List<SortObject> sortObjects = GetSortObjects(); // This is simplified, the data has a few different sources
IOrderedEnumerable<SortObject> orderedList = sortObjects.OrderBy(p => p.Cells["ArbitraryKey"]);
SortObject firstObject = sortedList.First();

// other work with 'orderedList' follows

The problem occurs when I'm trying to OrderBy objects of the DateTime type, and some of those objects are not set and default to 'System.DBNull'. In this case an exception is thrown when calling 'sortedList.First()' or in any of the later references to 'sortedList'. The exception is simple: "Object must be of type DateTime", which seems to be a consequence of OrderBy trying to compare the type DateTime to the type DBNull.

I've tried two solutions that haven't worked so far:

Attempt One: Set DBNull to new DateTime. In theory this should work, but I would need to create not simply DateTime type objects, but objects of any arbitrary type on the fly. (I'd also need to take note of these SortObjects and set their data back to DBNull once I had the order correct; I can't be actually changing data after all).

Attempt Two: Organize just DBNull, then just DateTime, then slap them together. Again this might work in theory, but the "other work" mentioned in the code snippet is extensive, including reordering using ThenBy() an arbitrary number of times on any key(s). Doubling its complexity is not an elegant solution and I consider it a backup.

What is the best way to resolve this?

PS: For OrderBy and DateTime I'm using the Microsoft .NET Framework v4.6.2

1

There are 1 best solutions below

0
On BEST ANSWER

Change the OrderBy statement to OrderBy(v => v is DBNull ? null : v)

OrderBy can handle nulls, but not dbNulls.

That code should work for all the data types