Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order-preserving data structures in C#

MSDN has no information on the order preserving properties of data structures. So I've been making the assumption that:

  • HashTable and HashSet do not preserve the insertion order (i.e. the "hash" in there is a giveaway)
  • Dictionary and List do preserve the insertion order.

From this I extrapolate that if I have a Dictionary<double, double> foo that defines a curve, foo.Keys.ToList() and foo.Values.ToList() will give me an ordered list of the scope and domain of that curve without messing about with it?

like image 215
Oren Mazor Avatar asked Apr 27 '10 15:04

Oren Mazor


People also ask

What data structure maintains order?

If we want to maintain the insertion order of the elements, we are supposed to use LinkedHashSet. LinkedHashSet maintains the order in which the elements are inserted.

Is order preserved in dictionary C#?

While Dictionary<TKey, TValue> clearly states that enumeration ordering is undefined, we tested that it indeed does preserve insertion ordering (at least as long as you do not remove items from it).

What kind of data structure allows retrieval in the same order as insertion?

In computer science, a queap is a priority queue data structure. The data structure allows insertions and deletions of arbitrary elements, as well as retrieval of the highest-priority element.

Do lists maintain order C#?

The List<> class does guarantee ordering - things will be retained in the list in the order you add them, including duplicates, unless you explicitly sort the list.


1 Answers

You should NOT expect either the keys or values in a regular Dictionary<TKey,TValue> to be maintained in any order. In a SortedDictionary<TKey,TValue> the keys and values are maintained in order by the value of the key - this is not the same as insertion order.

The only built-in dictionary in the .NET framework that preserves insertion order is System.Collections.Specialized.OrderedDictionary. Unfortunately, this class is not generic - however, it's not terribly hard to write a generic wrapper around it. Keep in mind, when dealing with value types (like int or double) it will result in boxing of the keys/values (generic dictionaries don't impose boxing on value types).

like image 171
LBushkin Avatar answered Sep 18 '22 02:09

LBushkin