LINQ查询选择最新记录

时间:2012-12-30 02:10:19

标签: database linq row

我们的表结构如下所示:

appointmentID    

1abc   --------------->1              
1abc (latest)  ------------>2            
1hjt               
990aa             
990aa              
990aa (latest             

DateTime start = DateTime.Now.AddDays(0);
DateTime end = DateTime.Now.AddDays(7));

List<JobCustomers> appointments = objectContext.JobCustomers.Where(
                    a => a.StartTime >= start && a.EndTime <= end && !string.IsNullOrEmpty(a.AppointmentId)).ToList();   

foreach (JobCustomers appointmentItem in appointments) {
    // HERE I WANT TO WRITE SOME CODE
    -- WHEN WE ARE INSERTING NEW RECORD OF A SAME ID EX "1abc" IT MUST 
    COMPARE WITH LATEST RECORD "-----2> 
}

我的要求:如果有超过1行具有相同的ID,那么我需要通过预约ID获取最新记录,如下所示

List<JobCustomers> appointments = objectContext.JobCustomers.Where(
                    a => a.StartTime >= start && a.EndTime <= end && !string.IsNullOrEmpty(a.AppointmentId).**take(0**)).ToList();

简单来说:当我们插入具有相同id的新记录时使用LINQ,我们需要与最后插入的记录进行比较

3 个答案:

答案 0 :(得分:0)

LINQ和SQL都不知道您插入数据的顺序,您需要有一个额外的字段来保存此顺序(可以是日期,也可以是自动数字)。完成后,您将可以使用:

YourList.OrderBy(i => i.Id).ThenByDescending(i => i.YourColumnToSaveOrder)

答案 1 :(得分:0)

var latestAppts = appointments.GroupBy(x => x.AppointmentId)
                              .Select(g => g.Last());

答案 2 :(得分:0)

如果我正确地阅读此内容,您就会尝试专门抓取带有相同ID的最新记录。这只需要使用LINQ的LastOrDefault扩展方法:

//Variable 'yourNewRecord' is what you're about to enter into the database
var latestAppt = objectContext.JobCustomers
                              .LastOrDefault(a => a.StartTime >= start && 
                                                  a.EndTime <= end &&
                                                  a.AppointmentID.Equals(yourNewRecord.AppointmentID)

编辑:有关LastOrDefault的详细信息,请查看MSDN链接here