开发者

Changing the Order in a .NET Generic Dictionary

I have a class that inherits from a generic dictionary as follows:

Class myClass : System.Collections.Generic.Dictionary<int, Object>

I have added a list of values to this in a particular order, but I now wish to change that order. Is there any way (without removing and re-adding) that I could effectively re-index the values; so change the object at index 1 to now be at index 10 for example? For example, this doesn't work:

m开发者_运维技巧yClass[1].Index = 10;


Dictionaries by themselves don't have an index order. Consider inheriting from the KeyedCollection class instead. It's a merge of a dictionary and an ordinary list, and it's designed to use a member of your items as the key, and have an index order.


Have a look at the SortedDictionary class where you can sort your items by the key.

Normally, you cannot change the index of items in Dictionary because it is against the principle ;-)


Dictionaries (or more generally hashtables) do not have indicies. This goes for all languages.


For purposes of enumeration, each item in the dictionary is treated as a KeyValuePair structure representing a value and its key. The order in which the items are returned is undefined.

Taken from MSDN.


Old topic, but nevertheless the answers are not all valid

You can use Linq to achieve this.

Dictionary<int, string> Breadcrumbs = new Dictionary<int, string>();
Breadcrumbs.Add(1, "Test1");
Breadcrumbs.Add(2, "Test2");
Breadcrumbs.Add(3, "Test3");
Breadcrumbs.Add(4, "Test4");
Breadcrumbs.Add(5, "Test5");

var q = Breadcrumbs.OrderByDescending(x => x.Key);

// And bind it
gridView.DataSource = q;
gridView.DataBind();


Take a look at this question. Not a duplicate but I think it fully applies to you. They suggest you have two collections: both a dictionary (for lookups) and a List (for keeping an order that isn't sortable). If these are reference types, then you shouldn't be too concerned about memory usage here since you're only duplicating pointers (unless, of course, you have a bajillion items in here).


Dictionary<> is an unordered collection, you'll only get the elements out of it in the order you put them in by accident. You'll need a SortedDictionary<>.


I have added a list of values to this in a particular order

There is no such thing like particular order for Dictionary. Perhaps you can look at SortedList. It supports indexing for keys and values but adding / removal are O(n) complexity vs O (log N) for SortedDictionary.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜