Benj
Benj

Reputation: 989

Order of Dictionary.Keys.ToArray() vs Dictionary.Values.ToArray()

I have a question regarding implementation details of Dictionary

Assume the following code:

private IDictionary<Int64, Int32> _data = new Dictionary<Int64, Int32>();

private void Foo() 
{
    Int64[] keys = _data.Keys.ToArray<Int64>();
    Int32[] vals = _data.Values.ToArray<Int32>();

    // Further code goes here
}

May I assume at this point, that

_dict[keys[i]] == vals[i]

for each i in [0 .. _data.Length-1], or might the order of both arrays be unrelated?

Upvotes: 0

Views: 146

Answers (1)

Enigmativity
Enigmativity

Reputation: 117057

Why not just do this?

private void Foo() 
{
    Int64[] keys = _data.Keys.ToArray<Int64>();
    Int32[] vals = _data.Keys.Select(k => _data[k]).ToArray<Int32>();

    // Further code goes here
}

It's still O(n) time and it won't break if .NET changes in the future.

Upvotes: 3

Related Questions