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.
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);
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");
...
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