Generic Key/Value pair collection in that preserves insertion order?

前端 未结 9 1276
刺人心
刺人心 2020-12-09 01:40

I\'m looking for something like a Dictionary however with a guarantee that it preserves insertion order. Since Dictionary is a hashtable, I do not think it does.<

9条回答
  •  心在旅途
    2020-12-09 02:04

    There actually is one, which is generic and has been around since .net 2.0. It's called KeyedCollection. However, it comes with the restriction that it constructs the keys from the values, so it is not a generic Key/Value pair collection. (Although you can of course use it like KeyedCollection> as a workaround).

    If you need it as an IDictionary, it has a .Dictionary property.

    A somewhat minor issue that I have with it is that it is an abstract class and you have to subclass it and implement:

    protected abstract TKey GetKeyForItem(TItem item)
    

    I'd rather just pass a lambda into the constructor for this purpose, but then again, I guess a virtual method is slightly faster than a lambda (any comments on this appreciated).

    Edit As the question came up in the comments: KeyedCollection preserves order, as it inherits from Collection, which does (it derives from IList. See also the documentation of the Add method: Adds an object to the end of the Collection.).

提交回复
热议问题