5

I am trying to write a program that would use a data structure/class that will hold multiple data entries for one key - this will be somehow similar to Dictionary but it's not one to one but one to many relation. I am trying to think of a class that I can use but I cannot figure anything out.

For instance how it may look like:

I have a parameter xValue and 3 different values in different files so i would have :

xValue, <1.txt, 1>
xValue, <2.txt, 2>
xValue, <3.txt, 3>

Any ideas ?

EDIT: I have figured this out - After all I can use

Dictionary< string , Dictionary<..., ... > >

, can't I ?

Patryk
  • 22,602
  • 44
  • 128
  • 244
  • indeed, you can use nested dictionaries, but if you don't need to know from which file does the `xValue` come, you can just take a `HashSet`. – Vlad Dec 10 '11 at 20:01

2 Answers2

4

As there is no multiset in .NET natively, I would go for

Dictionary<Key, HashSet<XValue>>

in your case.

If you are ok with using 3rd-party containers, you can look up the answers from here, e.g., Wintellect PowerCollections.

Community
  • 1
  • 1
Vlad
  • 35,022
  • 6
  • 77
  • 199
1

If you do not need modify this collection after initialization and just need to do search, you can leverage built in Lookup<TKey, TElement> class, but really this would be tricky and useful in rare cases when you already have IEnumerable<> instances and would flatten it to lookup data structure, anyway this is pretty useful to keep in mind that .NET provides such intersting class.

MSDN

Represents a collection of keys each mapped to one or more values. A Lookup<TKey, TElement> resembles a Dictionary<TKey, TValue>. The difference is that a Dictionary<TKey, TValue> maps keys to single values, whereas a Lookup<TKey, TElement> maps keys to collections of values.

You can not instantiate it explicitly and just can get instance of lookup using LINQ ToLookup() method. There are major restrictions so you can use this class as lookup data structure - doing search.

There is no public constructor to create a new instance of a Lookup. Additionally, Lookup objects are immutable, that is, you cannot add or remove elements or keys from a Lookup object after it has been created.

sll
  • 61,540
  • 22
  • 104
  • 156