有什么理由不使用字典
我正在与一位同事讨论是否最好使用字典并在结果集更改时重新填充它,或者每次都对列表中的所有元素使用 linq 循环。
我们正在尝试映射父/子关系,我建议使用 ParentID 作为字典键,并将字典值作为自定义对象。
我们通常需要迭代所有父级/子级并遍历列表。
在这种情况下你有什么理由不想使用字典吗?如果是的话你会用什么代替
I was having a discussion with a co-worker over whether it is better to use a Dictionary and repopulate it whenever a result set changes or to just use linq loop over all elements in the list each time.
We're trying to map a parent / child relationship, and I suggested using the ParentID as the dictionary key, and the dictionary value as the custom object.
We will usually be needing to iterate over all parent / children and run down the list.
Is there any reason why you wouldn't want to use a Dictionary in this circumstance? if so what would you use instead
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您确实需要每次都迭代整个集合,那么使用
Dictionary
不会有太多(如果有的话)好处。另一方面,如果您偶尔需要通过键来查找特定实例,则Dictionary
可能正是您所需要的。请注意,即使您使用的是字典,您仍然可以在需要时迭代值列表,因为不会比迭代普通的
List
增加太多“权重”,但是您可以如果需要的话,仍然具有词典功能。If you really do need to iterate over the whole collection every time, there would not be much (if any) benefit to having a
Dictionary
. On the other hand, if you occasionally need to locate specific instances by their keys,Dictionary
could be what you need.Note that even if you are using a Dictionary, you can still just iterate through the list of Values when needed, for not too much more 'weight' than iterating through a normal
List
, but then you'd still have the Dictionary capabilities, if needed.就性能而言,它实际上取决于您的具体应用程序,因此您必须进行测试。
Performance wise, it's really going to depend on your specific application, so you'll have to test.