Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Take 1 inside GroupBy in Linq [duplicate]

Tags:

c#

linq

I have a query which returns a number of records.

For Example:

  • Date is 26-Feb then 10 records are returned for this date.
  • Date is 27-Feb then 15 records are returned for this date.

Click to See Records

I used the following query:

 var sData = vehicle.GsmDeviceLogs
                    .Where(gs => gs.Speed > zeroSpeed && !gs.DigitalInputLevel1)
                    .OrderBy(gs => gs.DateTimeOfLog)
                    .ToList();

Now, I just want to fetch the first record for each date. i.e.

  • Date is 26-Feb - 1 Record.
  • Date is 27-Feb - 1 Record.
like image 986
user3355115 Avatar asked Mar 20 '23 10:03

user3355115


1 Answers

You gave the answer in your question itself, group by and then select the first. Technically you would translate it to linq as the following:

var sData = vehicle.GsmDeviceLogs
              .Where(gs => gs.Speed > zeroSpeed && !gs.DigitalInputLevel1)
              .OrderBy(gs => gs.DateTimeOfLog)
              .GroupBy(gs => gs.DateTimeOfLog)
              .Select(gs => gs.First())
              .ToList();
like image 160
middelpat Avatar answered Mar 22 '23 23:03

middelpat