C# Dictionary add entry with wrong order

时光毁灭记忆、已成空白 提交于 2019-12-25 03:54:23

问题


I add a new item into the RoutingList but after the first delete the order is wrong.

public Dictionary<int, Route> RoutingList = new Dictionary<int, Route>();

For example:

1,route
2,route
3,route
4,route
5,route

Now I delete the first one.

2,route
3,route
4,route
5,route

By adding the next item I get this list:

6,route
2,route
3,route
4,route
5,route

And after this the first one (6) will deleted. But this is wrong. I want to delete the No. 2.

Why?

int key = RoutingList.LastOrDefault().Key;
RoutingList.Add(key + 1, tmpRoute);

if (RoutingList.Count == 5)
{
    RoutingList.Remove(RoutingList.First().Key);
}

回答1:


The order of a standard dictionary is not to keep the items in order by default. If you want to retain the order and keep the fast lookup you need to use an OrderedDictionary.

Alternatively if you don't need quick lookups, or your key is always your index (it looks like it might be) simply look at using a list, which will be ordered:

List<Route> routes;
Route route = routes[key];



回答2:


You can't rely on the order of items in a dictionary. If you need to delete an entry with the lowest id an alternative to an OrderedDictionary would be to change change your query (I am not 100% sure this will compile as I don't have VS available right now, but you get the idea):

if (RoutingList.Count == 5)
{
    RoutingList.Remove(RoutingList.Keys.Min());
}



回答3:


Per the MSDN:

The capacity of a Dictionary is the number of elements the Dictionary can hold. As elements are added to a Dictionary, the capacity is automatically increased as required by reallocating the internal array.

This then sounds like the behavior of an ArrayList, where the order is not maintained. When you remove an item from the dictionary, the size of the internal array is not reduced. Therefore, the index remains open at the item that you removed until the next item gets added which goes into that empty index.



来源:https://stackoverflow.com/questions/24223344/c-sharp-dictionary-add-entry-with-wrong-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!