C# 按值对对象进行排序
我想保存一个 CollidableActor 对象列表,按其属性“.Position.X”排序。
我想知道最快(最有效)的方法是什么。起初我考虑使用 SortedDictionary,然后使用 SortedList,但我读到 SortedDictionaries 无论如何都更快。
现在我很困惑,因为我不知道我是否想要字典或列表。另外,在实现 IComparable 接口并创建 CompareTo() 方法时,仅返回 .Position.X 就足够了吗?
如果没有,是否有更好的结构或类可供我使用,根据 .Position.X 在添加/删除内容时快速对它们进行排序? (我会经常从列表中添加/删除对象;在添加对象时排序会更好,还是在使用列表之前进行更新排序更好?)。
谢谢。
编辑:事实上,由于所有对象都是唯一的,某种 HashSet 集合是否可取?谢谢。
I want to hold a list of CollidableActor objects, sorted by their property ".Position.X".
I am wondering on what would be the quickest (most efficient) method of doing this. At first I was thinking of using a SortedDictionary, and then a SortedList, but I read that SortedDictionaries are faster anyway.
Now I'm confused, because I don't know whether I want a dictionary or list. Also, when implementing the IComparable interface, and creating my CompareTo() method, would it be ample enough just to return .Position.X?
If not, is there a better structure or class that I could use that would sort things quickly as I add/remove them, according to .Position.X? (I will be adding/removing objects from the list a lot; would it be better to sort as the objects are added, or once an update, before I use the list?).
Thank you.
Edit: Infact, as all the objects will be unique, would some sort of HashSet collection be advisable? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我们可以通过在解决方案中对问题域进行建模来解决这个问题。考虑一下您的域,它是您想要在其上渲染可碰撞对象的画布/网格吗?您是否正在尝试解决调度问题?基于该设计您的数据结构。
让我们列出数据结构的目标 -
创建您自己的数据结构,通过在您自己的类中封装排序列表和哈希表来满足这些目标 -
公共类 MyCanvas
{
私有 IDictionary _positionMap = new SortedList();
私有 IDictionary _objectMap = new HashTable();
注意
- 请注意,代码可能无法编译,并且需要注意错误处理、线程问题等问题。
We can solve this by modelling the problem domain in the solution. Think about your domain, is it a canvass/grid on which you want to render your collidable objects, are you tring to solve a scheduling problem? Based on that design your data structure.
Lets list down the goals for our data structure -
Create your own data structure which meets these goals by encapsulating a sorted list and a hashtable in your own class -
public class MyCanvas
{
private IDictionary _positionMap = new SortedList();
private IDictionary _objectMap = new HashTable();
}
Note - please note that the code may not compile and concerns like error handling, threading issues etc needs to be taken care of.