在循环内循环

时间:2010-11-24 10:34:21

标签: c# optimization loops

嘿伙计们 - 我遇到了这个问题,我只是想知道处理它的最佳方法是什么。

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


       }

}

这是我能想到的最简单的方法,但我不确定它是否最有效!

任何帮助都会很棒 -

感谢。

4 个答案:

答案 0 :(得分:2)

可能可能预先对较短的列表进行分组;这应该会给你更好的性能 - 我找不到完全 big-O评级的引用,因为MSDN没有引用它们,但它可以是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);
    }
}

答案 1 :(得分:2)

这个怎么样?

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

对我来说,这似乎是一个清晰简洁的语法,它解释了它做得非常好。

另外,我认为这里的性能应该没问题,可能与原始代码大致相同。

答案 2 :(得分:0)

您可以使用linq从循环中删除嵌套,如下所示:

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

答案 3 :(得分: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