Home > Software engineering >  EF Core group by and order by
EF Core group by and order by

Time:12-12

I have an emp table with emps logged in I am trying to find current day when is the last time emp logged in below is the query I tried. group by each employees last login time and their details.

var result = this.EMP.Where(a => a.Time.Date == DateTime.Now.Date)
                     .GroupBy(a => a.empname)
                     .Select(g => g.OrderByDescending(a => a.Time))
                     .FirstOrDefault();

I am trying order by descending and taking top 1 for each employee. I am getting error

Collections in the final projection must be an 'IEnumerable

Can someone please help with this?

CodePudding user response:

try this

var result = this.EMP
          .Where(a => a.Time.Date == DateTime.Now.Date)
          .GroupBy(a => new { a.empname, a.Time})
          .OrderByDescending(a => a.Key.Time))
          .Select(g => new 
             {
             Empname= g.Key.EmpName,
             Time = g.Key.Time
             }).FirstOrDefalt();

CodePudding user response:

This is how i solved

  var empids= this.EMP
              .Where(a => a.Time.Date == DateTime.Now.Date)
              .GroupBy(a => new { a.empname})
              .Select(g =>g.Max(x => x.ID)).ToList();

and in another query

var emprecords=this.EMP.Where(e=>empids.Contains(e.ID))

         
  • Related