环内循环
问题描述:
嘿家伙 - 我坚持这个问题,我只是想知道什么是处理它的最好方法是。环内循环
Foreach (var customer in CustomerList)
{
Foreach (var appointment in AppointmentList)
{
if(appointment.customerId == customer.id)
customer.appointments.add(appointment)
}
}
这是我能想到的最简单的方法,但我不知道它是否最有效率!
任何帮助将很大 -
谢谢。
答
你可能也许预先分组较短的名单;这应该会给你更好的性能 - 由于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);
}
}
答
这个怎么样?
foreach (var customer in CustomerList)
{
customer.AddRange(appointment.Where(a => a.CustomerId == customer.id));
}
对我来说,这似乎是一个清晰简洁的语法,它解释了它的相当不错。
此外,我认为这里的性能应该没问题,并且可能与您的原始代码大致相同。
答
你可以使用LINQ移除循环嵌套,就像这样:
foreach (var customer in from customer in CustomerList
from appointment in AppointmentList
select customer)
{
// ...
}
答
你可以让你的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
这是否编译?我认为IGrouping没有索引器?你想使用ToLookup吗?如果你使用ToLookup,它应该是(几乎)O(n + m) – CodesInChaos 2010-11-24 10:49:09
@CodeInChaos - d'oh!我的确的意思是ToLookup – 2010-11-24 10:51:16