Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What data structure do I use here?

I have lots of instances two classes Children and Animal which have a many-to-many entity relationship.

I want to have a data structure such that given a Children I can get a list of Animal that are mapped to it and vice versa. For any given Animal I can get a list of Children that are mapped to it.

I need this data structure to be concurrent such that it can be accessed by any thread.

So given an example mapping:

Child1 -> Animal1
Child1 -> Animal2
Child1 -> Animal3
Child2 -> Animal2
Child2 -> Animal3
Child3 -> Animal3

Querying for Child1 I wish to get a returned list: [ Animal1, Animal2, Animal2 ].

Querying forAnimal2 I wish to get a returned list: [ Child2, Child3 ].

The only way I could think to do this was using a dictionary and a list for each item in this dictionary (both Animals and Children) but I would then also have to deal with locking an synchronization of the lists which is troublesome.

like image 342
Cheetah Avatar asked Mar 18 '13 13:03

Cheetah


Video Answer


2 Answers

I think you have to split up your data structure into three tiers.

Child <- ChildToAnimalRelation -> Animal

So Child and Animal both have collections of ChildToAnimalRelation

public class ChildToAnimalRelation 
{
    public Child Child { get; set; }
    public Animal Animal { get; set; }
}

Getting an animals children would be done as follows:

var children = currentAnimal.ChildToAnimalRelations.Select(r => r.Child);

vice versa:

var animals = currentChild.ChildToAnimalRelations.Select(r => r.Animal);
like image 173
Michael Schnerring Avatar answered Sep 20 '22 14:09

Michael Schnerring


How about using a list and then use Linq for query? One possible implementation:

List<Tuple<string, string>> allItems=new ...
allItems.Add(Tuple.Create("Child1", "Animal1");
...
var child1RelatedItems=allItems.Where(entry =>entry.Item1=="Child1");
var animal1RelatedItems=allItems.Where(entry =>entry.Item2=="Animal1");
...
like image 29
David Avatar answered Sep 22 '22 14:09

David