开发者

custom sorting of Hashtable in C# (not by keys)

I need to sort the data in a Hashtable by a property of the object added to the collection. how to do that? my project uses .NET 2.0, so I can't use any features that do not work by default in .NET 2.0 runtime (I may be able to use some of the C# 3.0 features that will work on .NET 2.0 without adding references to any new dlls). all the objects added to hashtable are of the sam开发者_Python百科e type. If I use SortedList and pass Hashtable to it (through constructor), then it sorts only by keys, is there a way to pass custom sorting logic to it?


if you are bound to .NET 2.0 you can use IComparer. http://codebetter.com/davidhayden/2005/02/27/implementing-icomparable-for-sorting-custom-objects/

a Hashtable is definetly the wrong datastructure if you want to sort something.


@Snoopy said IComparer, that is indeed what you need. Take a look at SortedDictionary.


Take a look at the drawbacks of a hash table. Then look at the advantages and determine if you are using the right data structure. If you very rarely sort, then you may be using the right data structure. In this case, sorting will require you enumerate the values and put them into a list. If sort if frequent, consider moving to a different data structure, like a search tree. If you rarely do lookups/searches, I would consider using an ordinary list.


One option, if you want to stick to creating a sorted list from the contents of a Hashtable, is to write a subclass of IComparer, overload the Compare method as needed, and create a Sorted list using:

SortedList s = new SortedList( new MyIComparer() );

Then add the elements of your Hashtable to the list accordingly.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜