Click to See Complete Forum and Search --> : map vs. SortedList


garf
October 22nd, 2004, 10:23 AM
I am rewriting a C++ application to C#, I came across a few issues:
How do I replace a multimap in C#, a SortedList does not take any duplicates?

How do I change the value of a SortedList as I iterate through it, The DictionaryEntry is read only does not let the value be modified?

Thanks

darwen
October 22nd, 2004, 11:28 AM
There's a mapping class in C# - a hashtable (System.Collections.Hashtable)

You can always write your own e.g.


using System;
using System.Collections;

class MultiHashTable
{
private Hashtable m_hashTable = null;

public MultiHashTable()
{
m_hashTable = new Hashtable();
}

public void Add(object key, object value)
{
ArrayList aValues = null;

if (m_hashTable.Contains(key))
{
aValues = m_hashTable[key];
}
else
{
aValues = new ArrayList;
m_hashTable.Add(aValues);
}

if (aValues.IndexOf(value) < 0)
{
aValues.Add(value);
}
}

public ArrayList this[object key]
{
get
{
if (m_hashTable.Contains(key))
{
return m_hashTable[key] as ArrayList;
}
else
{
return null;
}
}
}

public void Remove(object key, object value)
{
if (m_hashTable.Contains(key))
{
ArrayList aList = m_hashTable[key] as ArrayList;
aList.Remove(value);

if (aList.Count == 0)
{
m_hashTable.Remove(key);
}
}
}
}


Get the idea ?

And if you need it to be sorted, then replace the hashtable with a SortedList instead - the calls are the same.

Darwen.

garf
October 22nd, 2004, 11:41 AM
I can't replace it with a SortedList since a SortedList does not take duplicate Keys?
Does the Hashtable take duplicate Keys?

darwen
October 22nd, 2004, 04:05 PM
Replace it with the class that I've given you.

And if you need it sorted replace the Hashtable in the class I've given you with a SortedList.

That's why I gave you the code...

Darwen.