What data structure / class can I use to represent a one-to-many relationship?

I am trying to write a program that will use a data structure / class that will contain several data records for one key - this will somehow look like a dictionary, but this is not one to one, but one to many relationship. I am trying to think of a class that I can use, but I can’t understand anything.

For example, what it might look like:

I have an xValue parameter and 3 different values ​​in different files, so I would:

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

Any ideas?

EDIT: I figured it out - after all, I can use

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

is not it?

+4
source share
2 answers

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

 Dictionary<Key, HashSet<XValue>> 

in your case.

If you agree to the use of third-party containers, you can find the answers here , for example Wintellect PowerCollections .

+3
source

If you do not need to modify this collection after initialization and just need to search, you can use the built-in Lookup<TKey, TElement> , but in fact it would be difficult and useful in rare cases when you already have instances of IEnumerable<> and will smooth it down to the search data structure, anyway it is very useful to keep in mind that .NET provides such an intersting class.

MSDN

Represents a set of keys, each of which is mapped to one or more values. Lookup<TKey, TElement> is similar to Dictionary<TKey, TValue> . the difference is that a Dictionary<TKey, TValue> displays the keys for a single value, while a Lookup<TKey, TElement> displays the keys to collections of a value.

You cannot express it explicitly, and you can simply get a search instance using the LINQ ToLookup() method. There are serious limitations, so you can use this class as the structure of the search data - to perform a search.

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

+1
source

Source: https://habr.com/ru/post/1385650/


All Articles