views:

725

answers:

6

Hi,

I want to create a data store to allow me to store some data.

The first idea was to create a dictionary where you have 1 key with many values, so a bit like a one to many relationship

I think the dictionary only has 1 key value.

How else could I store this information??

Marc

+6  A: 

You can use a list for the second generic type. For example a dictionary of strings keyed by a string:

Dictionary<string,List<string>> myDict;
Oded
+3  A: 

You could use a Dictionary<KeyType,List<ValueType>>.

That would allow each key to reference a list of values.

Blorgbeard
+1  A: 

You can have a dictionary with a collection (or any other type/class) as a value. That way you have a single key and you store the values in your collection.

Maurits Rijk
A: 

A .NET dictionary does only have a 1-to-1 relationship for keys and values. But that doesn't mean that a value can't be another array/list/dictionary.

I can't think of a reason to have a 1 to many relationship in a dictionary, but obviously there is one.

If you have different types of data that you want to store to a key, then that sounds like the ideal time to create your own class. Then you have a 1 to 1, but you have the value class storing more that 1 piece of data.

Alastair Pitts
+4  A: 

Your dictionary's value type could be a List, or other class that holds multiple objects. Something like

Dictionary<int, List<string>> 

for a Dictionary that is keyed by ints and holds a List of strings.

A main consideration in choosing the value type is what you'll be using the Dictionary for, if you'll have to do searching or other operations on the values, then maybe think about using a data structure that helps you do what you want -- like a HashSet.

Tim Ridgely
+3  A: 

Use a dictionary of lists (or another type of collection), for example:

var myDictionary = new Dictionary<string, IList<int>>();

myDictionary["My key"] = new List<int> {1, 2, 3, 4, 5};
GraemeF