循环中的循环
嘿伙计们 - 我被这个问题困扰了,我只是想知道处理它的最佳方法是什么。
Foreach (var customer in CustomerList)
{
Foreach (var appointment in AppointmentList)
{
if(appointment.customerId == customer.id)
customer.appointments.add(appointment)
}
}
这是我能想到的最简单的方法,但我不确定它是否是最有效的!
任何帮助都会很棒 -
谢谢。
Hey guys - I'm stuck with this problem and im just wondering what the best way to handle it is.
Foreach (var customer in CustomerList)
{
Foreach (var appointment in AppointmentList)
{
if(appointment.customerId == customer.id)
customer.appointments.add(appointment)
}
}
this is the simplest way I can think to do it but im not sure if it's the most efficient!
Any help would be great-
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以将较短的列表预先分组;这应该会给你更好的性能 - 我找不到准确大O评级的引用,因为MSDN没有引用它们,但它可能是O(n + m) 而不是 O(n * m)。
那么你可以使用:
或者不使用 LINQ(来自评论):
You could perhaps pre-group the shorter list; this should give you better performance - I can't find citations to the exact big-O ratings since MSDN doesn't cite them, but it could be O(n + m) instead of O(n * m).
then you can use:
Or without LINQ (from comments):
这又如何呢?
对我来说,这似乎是一个清晰简洁的语法,它很好地解释了它的作用。
另外,我认为这里的性能应该很好,并且可能与您的原始代码大致相同。
What about this?
For me this seems like a clear and concise syntax, and it explains what it does quite good.
Also, I think the performance should be fine here, and probably around the same as your original code.
您可以使用 linq 从循环中删除嵌套,如下所示:
You could use linq to remove nesting from loops, like this:
您可以将您的
customerList
设为Dictionary
,而不是由
组成。然后,您不是循环列表,而是尝试获取值
这样,你就可以让 Dictionary 为你优化它。
请注意,如果您只执行此操作一次,则可能不值得进行太多优化除非您发现速度明显下降。 过早的优化并不值得付出努力
You could make your
customerList
aDictionary
instead consisting of<id, cust>
.Then, instead of looping the list you try to get the value
This way, you let Dictionary optimize it for you.
Do note that if you only perform this action once, it's probably not worth optimizing much unless you see a notable slowdown from it. Premature optimization is not really worth the effort