Take 1 inside GroupBy in Linq

I have a query that returns the number of records.

Example:

  • Date is February 26th, then 10 records are returned to this date.
  • Date is February 27th, then 15 records are returned for this date.

Click to view posts

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 get the first record for each date. i.e.

  • Record date February 26th - 1.
  • Record date February 27th - 1.
+4
source share
2 answers

You answered in your question, share, and then select the first. Technically, you translate it to linq as follows:

var sData = vehicle.GsmDeviceLogs
              .Where(gs => gs.Speed > zeroSpeed && !gs.DigitalInputLevel1)
              .OrderBy(gs => gs.DateTimeOfLog)
              .GroupBy(gs => gs.DateTimeOfLog)
              .Select(gs => gs.First())
              .ToList();
+7
source

DateTimeOfLog.Date ( DateTime, ), Select, :

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

( , , )

0

Source: https://habr.com/ru/post/1528934/


All Articles