Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which data structure/class I can use to represent one-to-many relation?

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 ?

like image 915
Patryk Avatar asked Dec 10 '11 12:12

Patryk


2 Answers

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.

like image 54
Vlad Avatar answered Sep 24 '22 16:09

Vlad


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.

like image 40
sll Avatar answered Sep 26 '22 16:09

sll