C# associative array

后端 未结 10 2144
时光取名叫无心
时光取名叫无心 2020-12-11 00:12

I\'ve been using a Hashtable, but by nature, hashtables are not ordered, and I need to keep everything in order as I add them (because I want to pull them out in the same or

相关标签:
10条回答
  • 2020-12-11 00:48

    There's no perfect solution before .NET 4.0. In < 3.5 You can:

    Use a generic SortedList with integer key-type, and value type of the most-derived common type of your items. Define an integer value (i, let's say) and as you add each item to the SortedList, make the key i++, incrementing it's value as you go. Later, iterate over the GetValueList property of the sorted list. This IList property will yield your objects in the order you put them in, because they will be sorted by the key you used.

    This is not lightening-fast, but pretty good, and generic. If you want to also access by key, you need to do something else, but I don't see that in your requirements. If you don't new to retrieve by key, and you add items in key order so the collection doesn't actually have to do its sorting, this is it.

    In .NET 4.0 you'll have the generic SortedSet Of T, which will be absolutely perfect for you. No tradeoffs.

    0 讨论(0)
  • 2020-12-11 00:48

    One alternative is to keep your ordered key values in an ordered structure like a List, the rest being still stored in a dictionnary.

    Then, when you need to access your data, just go through your sorted List and query your dictionnary along the way.

    0 讨论(0)
  • 2020-12-11 00:49

    look at sorted list http://msdn.microsoft.com/en-us/library/system.collections.sortedlist.aspx

    0 讨论(0)
  • 2020-12-11 00:50

    Use the KeyedCollection

    Its underlying base is a List but provides a dictionary lookup based on key. In this case your key is the strings. So as long as you aren't adding the same key twice you are fine.

    http://msdn.microsoft.com/en-us/library/ms132438.aspx

    0 讨论(0)
  • 2020-12-11 00:55

    The best way is to use the C# indexers. It is configurable to anything we like. We can pass an int, enum, long, double or anything we like.

    Just have to create a class and give it indexers and configure input and output parameters. It is a little more work but I think this is the only right way.

    Please see this MSDN link for more information how to use it.

    0 讨论(0)
  • 2020-12-11 00:57

    As Haxelit suggests, you might derive from KeyedCollection<TKey, TValue>. It actually uses a List underneath until you hit a certain threshold value, and then it maintains both a List and a Dictionary. If you can use a function to derive one of your keys from one of your values, then this is an easy solution. If not, then it gets pretty messy.

    0 讨论(0)
提交回复
热议问题