你可能也許預先分組較短的名單;這應該會給你更好的性能 - 由於MSDN沒有引用它們,所以我找不到引用大O的評級,但它可能是O(n + m)而不是O(n * m) 。
var apptsByCustomer = AppointmentList.ToLookup(appt => appt.customerId);
那麼你可以使用:
foreach (var customer in CustomerList) {
foreach(var appointment in apptsByCustomer[customer.id]) {
customer.appointments.add(appointment);
}
}
或者沒有LINQ(從評論):
// this bit is **broadly** comparable to ToLookup...
Dictionary<int, List<Appointment>> apptsByCustomer =
new Dictionary<int, List<Appointment>>();
List<Appointment> byCust;
foreach(Appointment appt in AppointmentList) {
if (!apptsByCustomer.TryGetValue(appt.customerId, out byCust)) {
byCust = new List<Appointment>();
apptsByCustomer.Add(appt.customerId, byCust);
}
byCust.Add(appt);
}
foreach (Customer cust in CustomerList) {
if (apptsByCustomer.TryGetValue(cust.id, out byCust)) {
foreach (Appointment appt in byCust) cust.appointments.Add(appt);
}
}
這是否編譯?我認爲IGrouping沒有索引器?你想使用ToLookup嗎?如果你使用ToLookup,它應該是(幾乎)O(n + m) – CodesInChaos 2010-11-24 10:49:09
@CodeInChaos - d'oh!我的確的意思是ToLookup – 2010-11-24 10:51:16