This StackOverflow answer completely describes that a HashSet
is unordered and its item enumeration order is undefined and should not be relied upon.
However,
This brings up another question: should I or should I not rely upon the enumeration order between two or more sebsequent enumerations? Given there are no insertions or removals.
For example, lets say I have added some items to a HashSet:
HashSet<int> set = new HashSet<int>();
set.Add(1);
set.Add(2);
set.Add(3);
set.Add(4);
set.Add(5);
Now, when I enumerate this set via foreach
, let us say I receive this sequence:
// Result: 1, 3, 4, 5, 2.
The question is: will the order preserve if I enumerate the set times and times again given I do no modifications? Will it always be the same?
Practically speaking, it might always be the same between enumerations, but that assumption is not provided for in the description of IEnumerable and the implementor could decide to return then in whichever order it wants.
Who knows what it is doing under the hood, and whether it will keep doing it the same way in the future. For example, a future implementation of HashSet might be optimized to detect low memory conditions and rearrange its contents in memory, thereby affecting the order in which they are returned. So 99.9% of the time they would come back the same order, but if you started exhausting memory resources, it would suddenly return things in a different order.
Bottom line is I would not rely on the order of enumeration to be consistent over time. If the order is important to you then do your foreach over set.OrderBy(x => x)
so that you can make sure it is in the order you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With