HashSet that preserves ordering

Viewed 28855

I need a HashSet that preserves insertion ordering, are there any implementations of this in the framework?

4 Answers

If you need constant complexity of Add, Remove, Contains and order preservation, then there's no such collection in .NET Framework 4.5.

If you're okay with 3rd party code, take a look at my repository (permissive MIT license): https://github.com/OndrejPetrzilka/Rock.Collections

There's OrderedHashSet<T> collection:

  • based on classic HashSet<T> source code (from .NET Core)
  • preserves order of insertions and allows manual reordering
  • features reversed enumeration
  • has same operation complexities as HashSet<T>
  • Add and Remove operations are 20% slower compared to HashSet<T>
  • consumes 8 more bytes of memory per item

You can use OrderedDictionary to preserve the order of insertion. But beware of the cost of Removing items (O(n)).

Related