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 ?
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.
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 aDictionary<TKey, TValue>
. The difference is that aDictionary<TKey, TValue>
maps keys to single values, whereas aLookup<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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With