Sorting Hashtable

V

vertigo

Hello

I defined:
Hashtable chan1 = new Hashtable(new
CaseInsensitiveHashCodeProvider(CultureInfo.InvariantCulture), new
InvariantComparer());

where:
public class InvariantComparer : IComparer
{
public CompareInfo m_compareInfo;
internal static readonly InvariantComparer Default = new
InvariantComparer();

internal InvariantComparer()
{
m_compareInfo = CultureInfo.InvariantCulture.CompareInfo;
}

public int Compare(Object a, Object b)
{/* compare my objects here */
DscRecord ra = a as DscRecord;
DscRecord rb = b as DscRecord;
if (ra.minute < rb.minute)
return 1;
else if (ra.minute > rb.minute)
return -1;

if (ra.second < rb.second)
return 1;
else if (ra.second > rb.second)
return -1;

if (ra.ssecond < rb.ssecond)
return 1;
else if (ra.ssecond > rb.ssecond)
return -1;

return 0;
}
}

but when i read data from hashtable:
IDictionaryEnumerator myEnumerator = chan.GetEnumerator();
while ( myEnumerator.MoveNext() )
{
......
}

i receive them "unsorted". Why ?
Is there any other way to read records from HashTable which is sorted by
key ?

Thanx
Michal
 
J

Jon Skeet [C# MVP]

vertigo said:
I defined:
Hashtable chan1 = new Hashtable(new
CaseInsensitiveHashCodeProvider(CultureInfo.InvariantCulture), new
InvariantComparer());

i receive them "unsorted". Why ?

Because hashtables are fundamentally unsorted. They're maps, not lists.
Is there any other way to read records from HashTable which is sorted by
key ?

Well, you could use SortedList (which is actually a map - don't let the
poor naming deceive you) instead. That's what it's there for.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top