F # LINQ lastOrDefault unix Epoch

I am learning LINQ with F #. I want to know how to use lastOrDefault. If I have a SQL Server data table called Days that stores 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 unixEpoch, which is time 00: 00:00 UTC 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

+4
source share
1 answer

The lastOrDefault returns the last date if the data table is not empty. Otherwise, the default value of DateTime is returned, which is DateTime.MinValue .

Since you cannot change this default value, it is better to check if the query result is the default value and returns outside the query limits:

 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, the return of Unix Epoch is not an F # -shaped way to handle exceptional cases. It is clearer to return None if there is no record in the data, and it is also easier to process this option value to eliminate 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 *) 
+4
source

Source: https://habr.com/ru/post/1393497/


All Articles