bardogodspeed
bardogodspeed

Reputation: 47

store parent-child relationship

I'm wondering how I can best store a set of values in C#, given a parent/child(ren) relationship. I've considered Dictionary, KeyValuePair, and List or perhaps defining a class. I might be overthinking this, but I want to make sure there's not a better way. I need to be able to do fast lookups. My dataset is such that the first item is the "parent", if you will, and the remaining items are related to the first. So:

G   H Y
Z   X A J

G is related to H and Y, Z is related to X, A and J. Pretty simple. But how do I best store these in C#? I could just have an array where the 0 index represents the parent. Is there a better way in C# to store this? It's much like a one-to-many relationship in SQL. But I have to accomplish this in code. My goal is to be able to easily pull a list of relatives based on the parent. So, given G, I should quickly be able to get H and Y. Do I use an Array, List<>... something else?

Upvotes: 2

Views: 1078

Answers (3)

Bernardo Bicalho
Bernardo Bicalho

Reputation: 96

i would use a hashtable object. performance is pretty neat as key values are calculated hashs and looking up values is done by calculating key and direct hit.

check this other posts that compares hashtables against dictionaries.

Which is faster to find an item in a hashtable or in a sorted list?

.NET HashTable Vs Dictionary - Can the Dictionary be as fast?

Why is Dictionary preferred over hashtable?

Upvotes: 0

Dima
Dima

Reputation: 6741

I suggest Lookup<TKey, TValue> (http://msdn.microsoft.com/en-us/library/bb460184.aspx).

A Lookup resembles a Dictionary. The difference is that a Dictionary maps keys to single values, whereas a Lookup maps keys to collections of values.

Upvotes: 0

malkassem
malkassem

Reputation: 1957

Dictionary<string, string[]> would be a good option for what you are talking about.

Upvotes: 1

Related Questions