字典或KeyedCollection?字典、KeyedCollection

2023-09-03 04:41:11 作者:逆流的鱼

我有一个类( SomeClass的),它包含的属性名称 字符串类型。我需要存储类的数组,并通过他们的名字找到它的项目。为此,有两种类型的集合: KeyedCollection 词典。我的问题是:有什么区别它们之间,在这种情况下,最好使用 KeyedCollection 词典?感谢您的解释任何帮助。

I have a class (SomeClass) which contains a property Name of string type. And I need to store an array of that class and find its items by their names. For this purpose there are two types of collections: KeyedCollection and Dictionary. My question is: What difference between them and in such case It is better to use KeyedCollection and Dictionary? Thanks for any help in explanation.

推荐答案

尽管如此previous意见解决两者之间最重要的区别的: KeyedCollection保持在它们被添加的顺序您的项目(添加的第一个项为索引0,最后添加的是最后的指数)。字典不(或至少它永远不会保证这样做)。

None of the previous comments address the most important difference between the two: KeyedCollection keeps your items in the order in which they are added (the first item added is at index 0 and the last added is at the last index). Dictionary does not (or at least it is never guaranteed to do so).

这额外的KeyedCollection的好处确实有一个小的性能开销。在幕后,你付出维护既有字典和费用清单。

This extra benefit of KeyedCollection does have a small performance cost. Under the covers, you pay the cost of maintaining both a Dictionary and a List.