4

I have a Dictionary with some simple string,string value pairs. The problem is that sometimes the key has to be empty for multiple items, which gives a dictionary error ->

 this key already exists.

Is there another class for this?

Also, I'm using .NET 2.0 so I can't use the Tuple class ...

while (nav.MoveToNext())
{
    if (nav != null)
    {
        if (!String.IsNullOrEmpty(nav.Value))
        {
            if (nav.HasChildren)
            {
                navChildren = nav.Clone();
                navChildren.MoveToFirstChild();
                if (navChildren != null)
                    if (!veldenToSkip.Contains(nav.LocalName.Trim().ToLower())
                        && !nav.LocalName.StartsWith("opmerkingen_"))
                        itemTable.Add(nav.LocalName.Replace("_", " "), navChildren.Value);
                         //normal key and value
                while (navChildren.MoveToNext())
                {
                    if (!veldenToSkip.Contains(nav.LocalName.Trim().ToLower()))
                    {
                        if (navChildren != null)
                        {
                            if (!String.IsNullOrEmpty(navChildren.Value))
                            {
                                itemTable.Add("", navChildren.Value);
                                //Add blank keys
                            }
                        }
                    }
                }
            }
        }
    }
}

I only want a structure like this:

value1    value2
value3    value4
          value5
          value6
value7    value8
...
Cœur
  • 37,241
  • 25
  • 195
  • 267
Run CMD
  • 2,937
  • 3
  • 36
  • 61
  • See http://stackoverflow.com/questions/1171812/multi-key-dictionary-in-c. – aligray Jun 10 '11 at 11:08
  • 1
    Why would you need a value pair in your dictionary without a Key? How will you find it afterwards? Consider not adding the value pair untill you have a key or turning your dictionary around (switching Key and Value). – InBetween Jun 10 '11 at 11:09
  • @aligray I don't think that's the same, he wants to allow multiple entries for the same key, not multiple keys per entry. – George Duckett Jun 10 '11 at 11:09
  • [Multimap](http://en.wikipedia.org/wiki/Multimap) – dtb Jun 10 '11 at 11:15
  • @Run CMD Perhaps you could show some example data? – aligray Jun 10 '11 at 11:15
  • 1
    And what do you want returned for an empty key (when mult. values are stored) ? – H H Jun 10 '11 at 11:29
  • well the Dictionary (or whatever class holds the structure) isn't used for future lookups or other data operations, it's only used as a data-placeholder to show the data on multiple outputs, Html, Pdf etc. – Run CMD Jun 10 '11 at 11:33

6 Answers6

6

you could implement the ILookup interface ...

wrap a Dictionary< TKey,List< TValue > >

DarkSquirrel42
  • 10,167
  • 3
  • 20
  • 31
  • Thanks, but the ILookup interface seems to be available from .NET 3.5 only, I'm using .NET 2.0 .... – Run CMD Jun 10 '11 at 11:36
4

Because having multiple values with the same key sort of negates the utility of a dictionary, a List of KeyValuePairs frequently makes more sense:

List<KeyValuePair<string, string>> itemTable = new List<KeyValuePair<string, string>>();
xr280xr
  • 12,621
  • 7
  • 81
  • 125
3

you can use a Dictionary<yourKeyType, List<yourObjectType>>. Like that you can add multiple items per Key... Before add you check if a List already exists for your key --> add it, otherwise create a new List. More elegant to wrap it in a class which handles it internally.

example of a class you could use:

class MultiValueDictionary<TKey, TValue>
{
    private Dictionary<TKey, List<TValue>> _InternalDict = new Dictionary<TKey, List<TValue>>();

    public void Add(TKey key, TValue value)
    {
        if (this._InternalDict.ContainsKey(key))
            this._InternalDict[key].Add(value);
        else
            this._InternalDict.Add(key, new List<TValue>(new TValue[]{value}));
    }

    public List<TValue> GetValues(TKey key)
    {
        if (this._InternalDict.ContainsKey(key))
            return this._InternalDict[key];
        else
            return null;
    }

}
fixagon
  • 5,506
  • 22
  • 26
2

Just generate a pseudo-key...

int emptyKey = 0;

...
if (!String.IsNullOrEmpty(navChildren.Value))
{
   string key = "Empty_" + emptyKey.ToString();
   emptyKey ++;
   itemTable.Add(key, navChildren.Value);
   //Add blank keys
}

You'll still have the Values, but note that a Dictionary does not preserve order (of Adding).

H H
  • 263,252
  • 30
  • 330
  • 514
1

try using Tuple:

http://sankarsan.wordpress.com/2009/11/29/tuple-in-c-4-0/

updated

ok now the post says .Net 2.0 so... this answer cannot work!

I think this can be useful:

Dictionary w/ null key?

Community
  • 1
  • 1
danyolgiax
  • 12,798
  • 10
  • 65
  • 116
1

Although very verbose, this could work:

class Pair<A, B>
{
    public A Key { get; set; }
    public B Value{ get; set; }
}

var items = new List<Pair<string, string>>();

items.Add(new Pair<string,string>() { Key = "", Value = "Test" });
items.Add(new Pair<string,string>() { Key = "", Value = "Test" });
aligray
  • 2,812
  • 4
  • 26
  • 35