Why is a Dictionary “not ordered”?

2019-01-03 00:28发布

I have read this in answer to many questions on here. But what exactly does it mean?

var test = new Dictionary<int, string>();
test.Add(0, "zero");
test.Add(1, "one");
test.Add(2, "two");
test.Add(3, "three");

Assert(test.ElementAt(2).Value == "two");

The above code seems to work as expected. So in what manner is a dictionary considered unordered? Under what circumstances could the above code fail?

7条回答
Bombasti
2楼-- · 2019-01-03 00:54

Dictionary< string, Obj>, not SortedDictionary< string, Obj >, is default to sequence by the insertion order. Strange enough you need to specifically declare a SortedDictionary to have a dictionary that sorted by key string order:

public SortedDictionary<string, Row> forecastMTX = new SortedDictionary<string, Row>();
查看更多
登录 后发表回答