Groups | Blog | Home
all groups > c# > december 2004 >

c# : how to store key value pairs ?


Peter Rilling
12/4/2004 11:24:22 AM
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.

[quoted text, click to view]

Manco
12/4/2004 9:22:10 PM
[quoted text, click to view]

Try SortedList.

Tom Gao
12/4/2004 11:09:49 PM
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

brucewood NO[at]SPAM canada.com
12/5/2004 12:25:12 AM
[quoted text, click to view]

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.
Jon Skeet [C# MVP]
12/5/2004 8:55:09 AM
[quoted text, click to view]

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.

--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet
Anders Borum
12/5/2004 12:19:49 PM
[quoted text, click to view]

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!

--
venlig hilsen / with regards
anders borum
--

AddThis Social Bookmark Button