none
How to retrieve last? RRS feed

  • Question

  • Hey Folks...

    I'm trying to retrieve the most recent entry from a table and evidentally I can't use "last"?  Can someone help me muddle through how to rewrite this?  What I had been trying was:

     

    var query = from n in DataContext.Posts

     

    where (n.PostedBy == UserID)

     

    group n by n.PostedBy;

     

    var lastpost = from g in query

     

    select g.Last();

     

    return lastpost;

    Thanks in advance for any help!

    Paul

    Tuesday, April 27, 2010 2:13 PM

Answers

All replies

  • Hi,

    You can order by any column (typically a date) in descending order and select the first record like this:

    ( from n in dc.Posts
    where n.PostedBy == userID
    orderby n.PostedDate descending
    select n ).First();

     

    Regards,


    Syed Mehroz Alam
    My Blog | My Articles
    Tuesday, April 27, 2010 2:25 PM
  • Try

    var lastpost = from g in query 
    select g.ToArray().Last(); 
    Tuesday, April 27, 2010 2:32 PM
  • Pretty much spot on... thank you VERY much Syed!  I'm very grateful!

    Paul

    Tuesday, April 27, 2010 3:00 PM
  • Try

    var
     lastpost = from
     g in
     query 
    select
     g.ToArray().Last(); 
    


    Hi John,

    Just a side note: Such query will work on LINQ to Objects (in memory collections) but Last() is not supported in Linq to SQL queries(as there is no TSQL equivalent). Have a look at this MSDN document particularly under the heading: Operators with No Translation .

    Regards,

     


    Syed Mehroz Alam
    My Blog | My Articles
    Wednesday, April 28, 2010 5:24 AM
  • Try

    var
    
     lastpost = from
    
     g in
    
     query 
    
    select
    
     g.ToArray().Last(); 
    
    


    Hi John,

    Just a side note: Such query will work on LINQ to Objects (in memory collections) but Last() is not supported in Linq to SQL queries(as there is no TSQL equivalent). Have a look at this MSDN document particularly under the heading: Operators with No Translation .

    Regards,

     


    Syed Mehroz Alam
    My Blog | My Articles


    Hi Syed,

    Thanks for the link - very helpful.

    Cheers,

    John.

    Wednesday, April 28, 2010 7:31 AM