Jesper Evertsson
Jesper Evertsson

Reputation: 613

I need to create a dictionary where each key can map to several values

Im trying to figure out how I can create something similar to a dictionary, but where each key can map to several values.

Basically what I need is to be able to assign multiple values to the same key without knowing in advance how many values each key will correspond to. I also need to be able to add values to an existing key on multiple occasions. It would also be nice if I could detect when a key + value combination already exists.

An example of how the program should work:

list.Add(1,5);
list.Add(3,6);
list.Add(1,7);
list.Add(5,4);
list.Add(1,2);
list.Add(1,5);

This should ideally produce a table like this:

1: 5, 7, 2

3: 6

5: 4

Is there any existing construction in C# that I can use for this or do I have to implement my own class? Implementing the class would probably not be a big problem, but Im a bit short on time so it would be nice if I could use something that already exists.

Upvotes: 1

Views: 225

Answers (4)

musefan
musefan

Reputation: 48415

Quick Solution

As you have already mentioned, a Dictionary would be the best type to use. You can specify both the key type and value type to meet your needs, in your case you want an int key and a List<int> value.

This is easy enough to create:

Dictionary<int, List<int>> dictionary = new Dictionary<int, List<int>>();

The challenge then comes with how you add records, you cannot simply do Add(key, value) because that will cause conflict which duplicate keys. So you have to first retrieve the list (if it exists) and add to that:

List<int> list = null;
if (dictionary.ContainsKey(key))
{
    list = dictionary[key];
}
else
{
    list = new List<int>();
    dictionary.Add(key, list);
}
list.Add(newValue);

Preferred Solution

This is obviously a few too many lines to use each time you want to add an item, so you would want to throw that into a helper function, or my preference would be to create your own class that extends the functionality of Dictionary. Something like this:

class ListDictionary<T1, T2> : Dictionary<T1, List<T2>>
{
    public void Add(T1 key, T2 value)
    {
        if (this.ContainsKey(key))
        {
            this[key].Add(value);
        }
        else
        {
            List<T2> list = new List<T2>() { value };
            this.Add(key, list);
        }
    }

    public List<T2> GetValues(T1 key)
    {
        if(this.ContainsKey(key))
            return this[key];
        return null;
    }
}

Which you can then use as easy as you originally wanted:

ListDictionary<int, int> myDictionary = new ListDictionary<int, int>();

myDictionary.Add(1,5);
myDictionary.Add(3,6);
//...and so on

Then to get the list of values for your desired key:

List<int> keyValues = myDictionary.GetValues(key);
//check if NULL before using, NULL means the key does not exist
//alternatively you can check if the key exists with if (myDictionary.ContainsKey(key))

Upvotes: 2

Adil
Adil

Reputation: 148110

You can use Dictionary<TKey, TValue>, the TKey would be int and TValue would be List<int>, You can add as many element in List as it grow autmatically.

Dictionary <int, List<int>> dic = new Dictionary<int, List<int>>();

The way you can access the value would change, you can for instance add element in dictionary like

void AddToYourCustomDictionary(int key, int someValue)
{
   if(!dic.ContainsKey(key))
   {
      dic.Add(key, new List<int>());
       dic[key].Add(someValue);
   }
   else  
     dic[key].Add(someValue); //Adding element in existing key Value pair
}

To access element in Dictionary Key -> value i.e list,

Console.WriteLine(dic[key][indexOfList]);

Upvotes: 1

Emran Sadeghi
Emran Sadeghi

Reputation: 612

Dictionary<int, List<int>> dictionary = new Dictionary<int, List<int>>();

public void AddIfNotExistInDic(int key, int Value) {
    List<int> list = null;
    if (dictionary.ContainsKey(key)) {
        list = dictionary[key];
    }
    else {
        list = new List<int>();
        dictionary.Add(key, list);
    }

    if (!list.Contains(Value)) {
        list.Add(Value);
    }
}

Upvotes: 1

NotJarvis
NotJarvis

Reputation: 1247

You can create a dictionary of Lists quite easily e.g.

Dictionary<int, List<int>> dictionary = new Dictionary<int, List<int>>()

An Alternative if you have created a list of items and want to separate them into groups with different keys, which serves much the same purpose is the Lookup class.

Upvotes: 1

Related Questions