循环遍历列表,高效找到编号最大的对象!
使用 C# 我有一个列表,这些对象都有一个在创建对象时随机化的浮动质量。
循环列表并找到质量最大的物体的最有效方法是什么?
using c# i have a list those objects all have a float mass that is randomized when the object is created.
Whats the most efficient way to loop through the list and find the object with the highest mass?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用简单列表执行此操作的最有效方法是简单的线性时间搜索,如
如果这是您打算定期执行的操作,则按质量排序的顺序存储对象和/或使用更合适的储存容器。
The most efficient way to do this with a simple list will be a simple linear time search, as in
If this is something you intend to do regularly, it may be beneficial to store your objects in an order sorted by mass and/or to use a more appropriate storage container.
听起来像是 morelinq 中 MaxBy/MinBy 运算符的完美候选者。您可以按如下方式使用它:
Sounds like a perfect candidate for the MaxBy/MinBy operators in morelinq. You could use it as follows:
实现 IComparable 将使事情变得简单且易于维护。我已经提供了一个例子。希望这有帮助。
我不确定这是否比循环更有效。我知道有时使用 linq 会在第一次调用时稍微降低性能。
但肯定很多时候可维护的代码得分比轻微的性能提升更高。有人可以提供有关并行执行与使用 AsParallel() 循环的性能的更多详细信息吗?
Implementing IComparable would make things simple and easy to maintain. I have provided an example. Hope this helps.
I am not sure if this is more efficient than looping. I understand that sometimes using linq slightly degrades the performance for the first time when it is invoked.
But definitely many a times maintainable code scores more over slight performance gain. Can someone provide more details on performance of PARALLEL execution vs looping with AsParallel().
最简单、最有效的解决方案(假设重复查询)是按大小对列表进行排序。
即
一旦列表排序,第一个元素将是最小的,最后一个元素将是最大的。
如果您希望按从大到小的顺序排列,可以使用 myList.Reverse()。
它运行在 o(nlog(n)) 中进行排序,然后找到最大的对象是
myList[myList.Count -1]
。对于 .net 列表来说是 o(1) (它们实际上是下面的数组)The simplest and most efficient solution (assuming repeated queries) is to sort the list by size.
i.e.
Once the list is sorted, the first element will be the smallest, and the last will be the largest.
You can use
myList.Reverse()
if you want it by largest to smallest.This runs in o(nlog(n)) to sort, and then finding the largest object is
myList[myList.Count -1]
. which is o(1) for .net lists (they are actually arrays underneath)如果您愿意用一点空间来换取时间,那么在一个实例构造函数中,可以使用如下所示的内容
,并且在创建对象时让调用方法传递这些参数。
If you're willing to trade a little space for time then, in one of the instance constructors, have something like the following
And upon object creation have the calling method pass those paramters.