4

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.
Sparkup
  • 3,686
  • 2
  • 36
  • 50
user3355115
  • 67
  • 1
  • 8

2 Answers2

7

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();
middelpat
  • 2,555
  • 1
  • 20
  • 29
0

You should group the records by DateTimeOfLog.Date (which returns a DateTime containing only the date part), and then get the first one of each group through a Select, like so:

var data = logs.Where( ... )
               .GroupBy( l => l.DateTimeOfLog.Date )
               .Select( g => new { Date = g.Key, Log = g.First() } );

(I used an anonymous type; you may prefer to use tuples depending on how you use that data)

Solal Pirelli
  • 1,199
  • 9
  • 21