Find Parent

Topics: Questions
Nov 20, 2013 at 9:24 AM
Hello

I have nested models. In every model I set the Parent property of the IParent Interface

And I try to find a parent. I don't know in which level I am. I only know the type of the parent.
Is it possible to find a parent of a special Type.
Coordinator
Nov 20, 2013 at 9:26 AM
There is no management whatsoever for models like with the view models.
Nov 20, 2013 at 10:25 AM
You don't need management for this. Only a FindParent() Method:

I have implemented such a method:
public static T FindParent<T>(IParent iam) where T : ModelBase
{
    var parent = iam.Parent;
    if (parent == null) return null;

    var parentT = parent as T;

    if (parentT != null) 
        return parentT;
            
    return FindParent<T>(parent);
}
or maybe better without recursion:
public static T FindParent<T>(IParent iam) where T : ModelBase
{
    while (true)
    {
        var parent = iam.Parent;
        if (parent == null) return null;

        var parentT = parent as T;

        if (parentT != null)
            return parentT;

        iam = parent;
    }
}
Waht do you think about to add it to catel?
Coordinator
Nov 20, 2013 at 8:24 PM
Looks like a great extension method to me. See https://catelproject.atlassian.net/browse/CTL-242
Nov 22, 2013 at 10:33 AM
Hello again.
I' am pleased you add it to catel.

And I also have a little change
public static T FindParent<T>(IParent iam) where T : IParent
{
    while (true)
    {
        var parent = iam.Parent;
        if (parent == null) 
            return default(T);

         if (parent is T)
             return (T)parent;

         iam = parent;
    }
}
I think its better to define the type T as IParent instead of ModelBase.
Coordinator
Nov 22, 2013 at 10:35 AM