how to store key value pairs ?

  • Thread starter Thread starter Tom Gao
  • Start date Start date
T

Tom Gao

if I wanted to store value in a key-value pair how do I do it ? I want to
keep them in order of A C B D... so this means I can't use sortlist and I
also can't use hashtable as it means I would lose ordering

Thanks
Tom
 
If you want to store strings, you could use NameValueCollection. If they
are objects, you could make your own strongly typed collection by inheriting
from NameObjectCollectionBase.
 
Tom said:
if I wanted to store value in a key-value pair how do I do it ? I
want to keep them in order of A C B D... so this means I can't use
sortlist and I also can't use hashtable as it means I would lose
ordering

Thanks
Tom

Try SortedList.
 
Tom Gao said:
if I wanted to store value in a key-value pair how do I do it ? I want to
keep them in order of A C B D... so this means I can't use sortlist and I
also can't use hashtable as it means I would lose ordering

Thanks
Tom

Simply create a class that implements the IComparer interface and pass
an instance of that class to the SortedList constructor. The
SortedList will then sort the entries according to the sort order of
the keys as defined in the Compare() method of your IComparer:

private class MyKeyComparer : IComparer
{
public MyKeyComparer()
{ }

public int Compare(object x, object y)
{
string key1 = (string)x;
string key2 = (string)y;
... establish your sort order here ...
}
}

then just say:

SortedList myList = new SortedList(new MyKeyComparer());

and you have a sorted list that sorts according to the order you
defined.
}
 
Tom Gao said:
if I wanted to store value in a key-value pair how do I do it ? I want to
keep them in order of A C B D... so this means I can't use sortlist and I
also can't use hashtable as it means I would lose ordering

I'd suggest keeping an ArrayList of the keys, and a Hashtable for the
mapping from key to value. You could encapsulate them both in your own
class, of course.
 
I'd suggest keeping an ArrayList of the keys, and a Hashtable for the
mapping from key to value. You could encapsulate them both in your own
class, of course.

I saw a quite good implementation of this description - I think it was on
the Source Forge website. I wonder if the 2.0 framework provides such a
class - seems like the question keeps popping up here.

If any of you have got the link to the implementation, please post it here.

Thanks in advance!
 
Back
Top