Is the IEnumerator of the dictionary guaranteed to be consistent?

So, I found the code snippet as follows:

class CustomDictionary { Dictionary<string, string> backing; ... public string Get(int index) { return backing.ElementAtOrDefault(index); //use linq extensions on IEnumerable } } 

And then it was used like this:

 for(int i=0;i<mydictionary.Count;i++) { var value=mydictionary.Get(i); } 

Besides the performance issues and the ugliness in this, is this code really correct? That is, IEnumerable on Dictionary is guaranteed to always return things in the same order, assuming nothing changes with the dictionary during the iteration?

+4
source share
3 answers

This is NOT guaranteed. Of course, this is for SortedDictionary <>, as well as for arrays and lists. But NOT for the dictionary.

Most likely, it will be stable if the dictionary is not changed, but it is simply not guaranteed. You have to ask yourself - are you lucky ?;)

+3
source

If you want to get items in the order in which they were inserted, you should probably look at Stack and Queue depending on which items you want first.

+1
source

Yes, you will receive the same items.

As you pointed out, the method you proposed is very inefficient.

ElementAtOrDefault is a LINQ extension method for IEnumerable, which means that for each element, it will iterate over all the paths to the specified element.

0
source

All Articles