Does Dictionary.Keys.List()[i] correspond to Dictionary.Values.ToList()[i]?
I have a Dictionary
data type. My开发者_运维百科 question is, is Dictionary.Keys.ToList()[i]
always correspond to Dictionary.Values.ToList()[i]
? That is, will the following test always passes
public void DictionaryTest(int i, Dictionary<U,T> dict)
{
var key = dict.Keys.ToList()[i];
Assert.AreEqual(dict[key], dict.Values.ToList()[i]);
}
I would say yes based on this from MSDN:
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.
Checking the MSDN entry for Dictionary.Keys Property:
The order of the keys in the Dictionary.KeyCollection is unspecified, but it is the same order as the associated values in the Dictionary.ValueCollection returned by the Values property.
Reflector says, that in Framework 2.0 - 4.0 both KeyCollection and ValueCollection are enumerating over dictionary.entries collection. That's why order will be the same. And by the way same order will be for enumerating over dictionary itself (KeyValuePairs).
In your code - yes. But if you override GetHashCode() into U Class and then made some changes that will change value of GetHashCode() and invoke Assert, it's possible that it will be false, cause Dictionary is implemented as a hash table. The next code returns false:
class Program
{
static void Main(string[] args)
{
Dictionary<A, int> d = new Dictionary<A, int>();
for (int i = 1; i <= 10; i++)
{
d.Add(new A { Hash = i}, i);
}
DictionaryTest(5, d);
}
public static void DictionaryTest(int i, Dictionary<A, int> dict)
{
A key = dict.Keys.ToList()[i];
key.Hash = 4;
Console.WriteLine(dict[key].Equals(dict.Values.ToList()[i]));
Console.ReadKey();
}
}
public class A
{
public int Hash { get; set; }
public override bool Equals(object obj)
{
return this.GetHashCode() == obj.GetHashCode();
}
public override int GetHashCode()
{
return Hash;
}
}
精彩评论