sol43
sol43

Reputation: 11

When retrieving the keys and values from a dictionary in c# are they guaranteed to share the same indexing?

Dictionary<string, int> dict = new Dictionary<string,int>();

dict.Add("one",1);
dict.Add("two",2);
dict.Add("three",3);
dict.Add("four",4);

List<string> keys = dict.Keys.ToList();
List<int> values = dict.Values.ToList();

From the code above if the list of keys looked like this { "two" , "four" , "three" , "one"} would the list of values always look like this { 2 , 4 , 3 , 1}

Upvotes: 0

Views: 61

Answers (2)

HarryPotter
HarryPotter

Reputation: 119

Yes, usually dictionaries maintain their order in the same order as the associated keys.

Upvotes: 0

Lee
Lee

Reputation: 144136

Yes according to the documentation:

The order of the values in the Dictionary.ValueCollection is unspecified, but it is the same order as the associated keys in the Dictionary.KeyCollection returned by the Keys property.

Upvotes: 2

Related Questions