Home > Software design >  How can I implement iterate in linear hierarchy?
How can I implement iterate in linear hierarchy?

Time:06-30

I have this class ( interface):

public interface IParentChiled
{
    IParentChiled Parent { get; }
    string Name { get; }
}

and there is method that should returns child's name prefixed with all its parents' names separated by the specified separator. something like : parent/child. the method is like this:

 public string GetFullName(IParentChiled child, string separator = null)
 {
        separator ??= "/";
        throw new NotImplementedException();
 }

My Questions are :

1. What is the name of this type of Class/Interface that use itself as property?

2. How can I impalement the Method?

CodePudding user response:

To get a string like

Root/Parent/Child

you can

  1. Enumerate items (you can easily do it in Child, Parent, Root order).
  2. Reverse the enumeration.
  3. Join the items into the final string.

Possible implementation:

using System.Linq;

...

// static: we don't want "this" in the method
public static string GetFullName(IParentChiled child, string separator = null) {
  // Enumerate Names but in reversed order      
  static IEnumerable<string> Items(IParentChiled last) {
    for (IParentChiled item = last; item != null; item = item.Parent)
      yield return item.Name;
  }

  return String.Join(separator ?? "/", Items(child).Reverse());
}

You can implement this as an extension method for the IParentChiled interface:

using System.Linq;

...

public static class ParentChiledExtensions {
  public static string GetFullName(this IParentChiled child, string separator = null) {
    // Enumerate Names but in reversed order      
    static IEnumerable<string> Items(IParentChiled last) {
      for (IParentChiled item = last; item != null; item = item.Parent)
        yield return item.Name;
    }

    return String.Join(separator ?? "/", Items(child).Reverse());
  }
}

No you can use GetFullName method as if it's implemented by interface:

IParentChiled item = ...

Console.Write(item.GetFullName("."));

CodePudding user response:

there may be better solutions but i'd do something like this:

public string GetFullName(IParentChiled child, string separator = null){
    separator ??= "/";
    var parent = child;
    string name = child.name;
    while(parent.parent!=null){
        parent = parent.parent;
        name = parent.name   separator   name;
    }
    return name;
}
  • Related