Question

I am learning LINQ with F#. I want to know how to use lastOrDefault. If I have a SQL Server data table called Days, which store some date, I want to write a query to select the last date of the table, if there is no record, I want to return the unixEpoch, which is the time 00:00:00 UTC on 1 January 1970.

let lastDate =
    query {
          for day in days do
          lastOrDefault
          }

Let me know how to return unixEpoch, if there is no record in the data table.

Thanks, John

Was it helpful?

Solution

The lastOrDefault operator here returns the last date if the data table is not empty. Otherwise, it returns the default value of DateTime, which happens to be DateTime.MinValue.

Since you cannot alter this default value, it's better to check whether the query result is the default value and return outside the query:

let lastDate =
    let d =
       query {
               for day in days do
               lastOrDefault
          }
    if d = DateTime.MinValue 
    then new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
    else d

However, returning Unix Epoch isn't the F#-ish way of handling exceptional cases. It's clearer to return None if there is no record in the datatable, and it's also easier to process this option value to deal with an unexpected situation:

let lastDate =
    let d =
       query {
               for day in days do
               lastOrDefault
          }
    if d = DateTime.MinValue then None else Some d

match lastDate with
| None -> (* Process the exceptional case *)
| Some d -> (* Do something with d *)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top