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
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 beDateTime.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:
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 thisoption
value to deal with an unexpected situation: