进行比较。
我们的表结构如下所示:
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,我们需要与最后插入的记录
LINQ和SQL都不知道插入数据的顺序,您需要有一个额外的字段来保存这个顺序(可以是日期,也可以是自动数字)。一旦你有了,你就可以使用:
YourList.OrderBy(i => i.Id).ThenByDescending(i => i.YourColumnToSaveOrder)
var latestAppts = appointments.GroupBy(x => x.AppointmentId)
.Select(g => g.Last());
如果我正确地阅读了这一点,您正试图特别抓取与所带来的相同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链接