除了使用 List.Single 获取具有主键的元素之外,还有其他选择吗?
我的数据存储中有一个用户对象列表。
现在,一旦它已经在内存中,通过 ID 获取用户的唯一方法就是使用 Single 扩展方法。这确实是性能下降。
我知道我可以使用字典而不是列表,但这会是多余的。我必须将主键存储两次。那么还有另一种方法可以做我想做的事吗?
顺便说一句,我正在制作一个可以执行类似操作的自定义类,但我希望有一些开箱即用的东西。
I have a List of User objects from my data store.
Now once it is already in memory the only way to get a user by his ID is to use the Single extension method. This is really performance degrading.
I know I could have used a dictionary instead of a list but this would be redundant. I would have to store the Primary Key 2 times. So is there another way to do what i want?
BTW I am making a custom class that can do something like this, but i was hoping for something out of the box.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设主键是引用类型,您只需存储对主键的引用两次。
您是否尝试过使用
Dictionary<,>
并发现它效果不够好?这当然是最自然的解决方案。KeyedCollection<,>
(由 Mark 建议)当然也可以工作,但需要您从该类派生 - 而且我不想保证它实际上会节省任何内存。 (您需要了解实现细节 - 例如,它可以轻松地在内部使用字典。)Assuming the primary key is a reference type, you'd only be storing a reference to the primary key twice.
Have you tried using
Dictionary<,>
and found it doesn't work well enough? It's certainly the most natural solution.KeyedCollection<,>
(suggested by Mark) would certainly work too, but requires you to derive from the class - and I wouldn't like to guarantee it'll actually save any memory. (You'd need to know the implementation details - it could easily just use a Dictionary internally, for example.)您可以将内存中的用户保存在 KeyedCollection 中。
You could save your in-memory users in a KeyedCollection.