简体   繁体   中英

Entity Framework - GroupBy then OrderBy

I have a group of records that includes PatientID and Appointment Date.

I would like to group them by PatientID and order the groups by the oldest appointment in each PatientID group. Like this...

 ID     ApptDate
----------------------
  3    2/5/2005   (oldest compared to all groups , so group "ID = 3" is sorted first)
  3    5/10/2006
  3    6/2/2010

  1    8/5/2007
  1    9/1/2015 

  2    6/15/2009
  2    9/19/2009        

I'm pretty sure I need to use grouping first to obtain the oldest date value for each ID and then order by that value but I am stuck understanding how the two functions will work together.

var query = from a in db.Appointments
group a by new { a.Id, a.ApptDate} into pa
select new { 
     ID = pa.Key.Id,  
     Date = pa.Min(x =>x.ApptDate) ...

... but I crash and burn at this point.

Any help appreciated.

You requirements are as follows (though the question does not mention one of them, but it is apparent from how data is laid out):

  1. Group based on patient ID.
  2. Sort groups based on oldest appointment date in each group.
  3. Sort data within a group based on appointment date.

var query = records.GroupBy(r => r.PatientId) // Group patients .OrderBy(g => g.Min(r => r.AppointmentDate)) // sort groups by oldest record in each .Select(g => new { PatientId = g.Key, Records = g.OrderBy(r => r.AppointmentDate) // sort records within a group by oldest });

I modified a bit Tanveer Badar's answer to return a row for each entity.

Create a class for your return data

public class ReturnType
{
    public int ID { get; set; }
    public DateTime AppDate { get; set; }
}

Get a group of IDs and enumerable of ordered dates

var result = db.Appointment
            .GroupBy(a => a.Id)
            .OrderBy(a => a.Min(n => n.Date))
            .Select(a => new { ID = a.Key, AppDates = a.OrderBy(na => 
na.Date).Select(ne => ne.Date) })
            .ToList();

Then flatten the returned list. I tried with SelectMany but with no success.

var results = new List<ReturnType>();
        foreach (var a in result)
        {
            foreach (var date in a.AppDates)
            {
                var returnType = new ReturnType
                {
                    ID = a.ID,
                    AppDate = date
                };

                results.Add(returnType);
            }
        }

In my case it works fine...

var query = from a in db.Appointments
    group a by new { a.Id, a.ApptDate} into pa
    select new { 
         ID = pa.Key.Id,  
         Date = pa.Max(x =>x.ApptDate)
       }).Select(x=>new { 
                             x.ID,x.Date
                            }).ToList();
db.Appointments.GroupBy(new {ID = item.ID, ApptDate = item.ApptDate}).OrderByDescending(item => item.ApptDate)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM