HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Parent with N-Childs where each child can have N-Childs

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
caneachwithchildswhereparentchildhave

Problem

I know my question sounds strange but I have a situation in which I have Parent Data which can have 'N' Childs and each child can further have N-Childs and so on.

So its Like.

-
Parent

a. Child

i. Child
    ii. Child


b. Child

i.Child


I hope I've made myself Clear. So here is a snapshot of the Database Table:

So I have wrote this Code to get my Data From Database. It is a recursive Function:

public static List GetCaseCommunicationByCustomerCaseId(int customerCaseId)
        {
            var parentCaseCommunications =
                EntityHandler.GetEntitiesContext().CaseCommunications.Where(x => x.CustomerCaseId == customerCaseId && x.ParentCaseCommunicationId == null);

            var mappedParentCommuncations = Mapper.Map>(parentCaseCommunications).ToList();

            foreach (var parent in mappedParentCommuncations)
            {
                parent.ChildCommunications = GetListOfChildCommunicationsByParentId(parent.CaseCommunicationId);
            }

            return mappedParentCommuncations;
        }

        public static List GetListOfChildCommunicationsByParentId(int caseCommunicationId)
        {
            var childCommunications =
                EntityHandler.GetEntitiesContext().CaseCommunications.Where(x => x.ParentCaseCommunicationId == caseCommunicationId);

            var mappedChild = Mapper.Map>(childCommunications).ToList();

            foreach (var child in mappedChild)
            {
                child.ChildCommunications = GetListOfChildCommunicationsByParentId(child.CaseCommunicationId);
            }

            return mappedChild;
        }


This is the function called from the other class: GetCaseCommunicationByCustomerCaseId

While GetListOfChildCommunicationsByParentId is the recursive function.

I was just need to know is there a better way of writing this?

Is this efficient?

Solution

It's not strange at all. It's just a tree, or graph, which is very common.

You don't even need two methods: a single one is sufficient. You should define a single recursive method that takes in a list (or some other collection) of id's and returns those id's and all their children and grand-children, etc. If you want the children of a single element instead of a list of id's, you can just pass a list of one element (or define a method that does that).

Actually, it might be better to use a set instead of list of id's as the argument to the method since it would then handle duplicates and circular references. ALso, if you use a list instead, you would have to specify in the documentation what the ordering of the returned list means.

Context

StackExchange Code Review Q#69190, answer score: 2

Revisions (0)

No revisions yet.