Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get last element with linq to sql

I have this:

var result = (from t in MyDC
              where t.UserID == 6
              orderby t.UpdateTime
              select t.ID).Last();

Basically, I'm using Linq-to-Sql and it doesn't support the .Last operator. I could retrieve all the records of the user and then using linq to objects to get my value but I'm wondering how to do this with linq-to-sql and return only one record.

Thanks for your suggestions.

like image 279
frenchie Avatar asked Jun 07 '11 19:06

frenchie


People also ask

How to get Last element in LINQ?

Get the last element from a sequence using the Linq Last() method. The following is our array. int[] val = { 10, 20, 30, 40 }; Now, get the last element.

How to use Last in LINQ?

The Last<TSource>(IEnumerable<TSource>) method throws an exception if source contains no elements. To instead return a default value when the source sequence is empty, use the LastOrDefault method.

How do you select the record with the highest date in Linq?

MaxBy(p => p. Age);


1 Answers

Just order by descending and use .First() instead:

var result = (from t in MyDC  
          where t.UserID == 6
          orderby t.UpdateTime descending
          select t.ID).First();
like image 127
Kirk Woll Avatar answered Oct 13 '22 09:10

Kirk Woll