2010-11-24 209 views
2

嘿傢伙 - 我堅持這個問題,我只是想知道什麼是處理它的最好方法是。環內循環

Foreach (var customer in CustomerList) 
{ 
     Foreach (var appointment in AppointmentList) 
     { 
     if(appointment.customerId == customer.id) 
      customer.appointments.add(appointment) 


     } 

} 

這是我能想到的最簡單的方法,但我不知道它是否最有效率!

任何幫助將很大 -

謝謝。

回答

2

可能也許預先分組較短的名單;這應該會給你更好的性能 - 由於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); 
    } 
} 
+0

這是否編譯?我認爲IGrouping沒有索引器?你想使用ToLookup嗎?如果你使用ToLookup,它應該是(幾乎)O(n + m) – CodesInChaos 2010-11-24 10:49:09

+0

@CodeInChaos - d'oh!我的確的意思是ToLookup – 2010-11-24 10:51:16

2

這個怎麼樣?

foreach (var customer in CustomerList) 
{ 
    customer.AddRange(appointment.Where(a => a.CustomerId == customer.id)); 
} 

對我來說,這似乎是一個清晰簡潔的語法,它解釋了它的相當不錯。

此外,我認爲這裏的性能應該沒問題,並且可能與您的原始代碼大致相同。

0

你可以使用LINQ移除循環嵌套,就像這樣:

foreach (var customer in from customer in CustomerList 
     from appointment in AppointmentList 
     select customer) 
{ 
    // ... 
} 
0

你可以讓你的customerList一個Dictionary,而不是由<id, cust>

然後,而不是循環的列表中,您try to get the value

Dictionary<int, Customer> customerList = new Dictionary<int, Customer>(); 
// populate your list 
// ... 
foreach (var appointment in AppointmentList) 
{ 
    Customer customer; 
    if (customerList.TryGetValue(appointment.customerID, out customer)){ 
     // found the customer 
     customer.appointments.add(appointment) 
} 

這樣,你讓字典優化它。
請注意,如果您僅執行一次此操作,則可能不值得優化很多,除非您看到其明顯的減速Premature optimization is not really worth the effort