我有一组包含PatientID和约会日期的记录。
我想通过PatientID对它们进行分组,并按每个PatientID组中最早的约会对这些组进行排序。像这样......
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
我非常确定我需要首先使用分组来获取每个ID的最早日期值,然后按该值排序,但我不明白这两个函数将如何协同工作。
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) ...
...但此时我崩溃并燃烧。
任何帮助表示赞赏。
答案 0 :(得分:0)
您的要求如下(虽然问题没有提及其中一个,但从数据的布局方式来看很明显):
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
});
答案 1 :(得分:0)
我修改了一点Tanveer Badar的答案,为每个实体返回一行。
为返回数据创建一个类
public class ReturnType
{
public int ID { get; set; }
public DateTime AppDate { get; set; }
}
获取一组ID和可枚举的有序日期
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();
然后展平返回的列表。我试过SelectMany但没有成功。
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);
}
}
答案 2 :(得分:-1)
就我而言,它运作正常......
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();
答案 3 :(得分:-1)
db.Appointments.GroupBy(new {ID = item.ID, ApptDate = item.ApptDate}).OrderByDescending(item => item.ApptDate)