user1613512
user1613512

Reputation: 3650

Parent child loop, design pattern

Let's say I have two classes (using C#).

Class A and B. Class A can be converted to B. Class B has a property Parent (of type B). I have a List<A> of A instances which I want to convert to a List<B>.

The class A contains information to know which instance of B is the parent.

Let's say I loop trough my List<A> to convert it.

for(int i =  0; i < listOfA.Count;i++)
{
    listOfB.Add(ConvertToB(listOfA[i], listOfB));
}

The method ConvertToB creates a B instance and searches the listOfB if it's parent is already in.

So let's say our ConvertToB looks like this:

public B ConvertToB(A a, List<B> listOfB)
{
   B newInstanceOfB = A as B;
   B.Parent = listOfB.FirstOrDefault(x => x.Id == a.ParentId);
}

This code will go wrong if the parent is not yet converted. F.ex if we convert listofA[1] , it's corresponding parent will be listofB[6]. Which won't be available at the time we want to convert listofA[1].

My question is how would one solve this problem in a clean object oriented way. What design pattern (GOF) can be used to tackle this problem.

Edit:

A is an attribute with some properties that B also has. A and B aren't related. B can also have a list of allowed children. This List<B> consist of items that are part of the listofB list.

So f.ex: listofA[0] will be converted to listofB[0]. listofB[0] has a parent listofB[4] and allowed children {listofB[7], listofB[8]}

Sorry for not mentioning this earlier.

Upvotes: 0

Views: 319

Answers (2)

Dario Scoppelletti
Dario Scoppelletti

Reputation: 559

The conversion from listOfA to listOfB is too complex to be merely a loop: you should encapsulate it in a method, let's say:

public List<B> ConvertToListOfB(List<A> listOfA)
{
   // The previous answer is quite good
}

If you want to add more than one listOfA to the same listOfB, you can use an extension method for class List<B>:

public static class ListOfBEx
{
    static void appendAll(this List<B> instance, List<A> listOfA) 
    {
        // almost the same implementation
    }
}

Encapsulation is good because after the first loop the new instances of B is in a incomplete state (missing the Parent).

Upvotes: 0

Euphoric
Euphoric

Reputation: 12859

Do you really need a design pattern? You can just do 2 loops. First will create the B instances and second will find&set the parents. You could even use bits of LINQ.

var listOfB = listOfA.Cast<B>().ToList()

foeach(var b in listOfB)
{
    b.Parent = listOfB.FirstOrDefault(x => x.Id == b.ParentId); // this will work because there is clear inheritance so B has all properties A has
}

Upvotes: 2

Related Questions