none
retrieving first and last database entries RRS feed

  • Question

  • I have a database that contains time series data that changes from day to day / week to week.  I would like to provide the user with a display that tells them what the first and last available DateTime is.  My question is: How do I write I LINQ query to tell me what the first and last date/time in a database table is?

    Thursday, January 27, 2011 7:49 PM

Answers

  • If the dates are consecutive then simply call the extension method First() and Last(). You may need to call AsEnumerable() first in some situations such as

     

    myContext.MyTables.AsEnumerable().Last();

     

    If the dates are sequential then you need to order them such as

    var items = (PurchaseOrderDetails.OrderByDescending ( pod=> pod.DueDate)).AsEnumerable().First (); // *Reveresed date* this is the first row, but last datetime.

     

     

    HTH


    William Wegerson (www.OmegaCoder.Com)
    • Marked as answer by digiplant Monday, January 31, 2011 9:33 PM
    Friday, January 28, 2011 3:41 PM
    Moderator

All replies

  • Are the stored times sequential, in other words in each row is the time ascending from the first?
    William Wegerson (www.OmegaCoder.Com)
    Thursday, January 27, 2011 10:50 PM
    Moderator
  • Hi OmegaMan, yes all the DateTimes are in sequential order.
    Friday, January 28, 2011 1:22 PM
  • If the dates are consecutive then simply call the extension method First() and Last(). You may need to call AsEnumerable() first in some situations such as

     

    myContext.MyTables.AsEnumerable().Last();

     

    If the dates are sequential then you need to order them such as

    var items = (PurchaseOrderDetails.OrderByDescending ( pod=> pod.DueDate)).AsEnumerable().First (); // *Reveresed date* this is the first row, but last datetime.

     

     

    HTH


    William Wegerson (www.OmegaCoder.Com)
    • Marked as answer by digiplant Monday, January 31, 2011 9:33 PM
    Friday, January 28, 2011 3:41 PM
    Moderator