Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq query to get the last record

I know this is asked many times and I've searched most of the solutions online, but nothing seems to make it for me. I have a table with this structure:

ID | ScheduleId | Filename | Description
 1 |     10     |          |  ....
 2 |     10     | test.txt |  .....

I want to get the last non-empty Filename by passing the ScheduleId(e.g. to get "test.txt" in this case).

I've tried many things and nothing seems to get me the Filename. Here is the last one:

var tempFileName = objContext.SchedulesAndFiles
                           .Where(x => x.ScheduleId == scheduleId)
                           .OrderByDescending(x => x.ScheduleId)
                           .Take(1).Select(x => x.Filename);

This doesn't work as well, although I understand why it doesn't:

var tempFileName = from e in objContext.SchedulesAndFiles
                   where e.ScheduleId == scheduleId 
                   orderby e.ScheduleId descending
                   select e.Filename;

Calling .Last() or .LastOrDefault() throws an exception(The query operator 'LastOrDefault' is not supported.)

like image 821
Apostrofix Avatar asked Nov 29 '22 15:11

Apostrofix


2 Answers

if have to include that you want only non-empty filenames. You may also use ToList() to finalize the query, then FirstOrDefault() should work as expected, try

var tempFileName = objContext.SchedulesAndFiles
                             .Where(x 
                                 => x.ScheduleId == scheduleId 
                                 && x.Filename != null 
                                 && x.Filename != "")
                             .OrderByDescending(x => x.ScheduleId)
                             .Take(1)
                             .Select(x => x.Filename)
                             .ToList()
                             .FirstOrDefault();
like image 77
esskar Avatar answered Dec 21 '22 08:12

esskar


You should sort your records based on the ID instead of ScheduleId and also filter the records that has the empty Filename:

objContext.SchedulesAndFiles
          .Where(x => x.ScheduleId == scheduleId && x.Filename != "")
          .OrderByDescending(x => x.ID)
          .First().Filename;
like image 28
Selman Genç Avatar answered Dec 21 '22 06:12

Selman Genç