开发者

VB.NET Dictionary.Add method index

When I call mydictionary.Add(key, object), can I guarantee that the object is added to the end of the dictionary in the sense that mydictionary.ElementAt(mydictionary.Count - 1) returns that object? I'm asking because I'm used to Java where HashMap doesn't have any order at all.

I'm hoping to use the ordering given by ElementAt as a way of knowing the order in which objects were added to the dictionary without using a separate data structure.

Update: Looks like Ele开发者_开发问答mentAt isn't going to be of any use. Is the best way to do this to use a separate data structure to store the ordering that I need?

Thanks


There is no order to a dictionary. The ElementAt method is a linq extension method that iterates over the dictionary using IEnumerable and counts the number of things, there is no relation to the order things were added.

There is a SortedDictionary, which will sort things by key, but will not keep them in the order they were added in.

If the order is really important you could always have two data structures, a list that you add the object to and a dictionary that stores the key to list index mapping. Or put a field inside your object that set from a counter as you add it to the dictionary.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜