显示树结构Table的前置符号

/// <summary>
 /// IAdaptable 可适配的接口
 /// </summary>
 public interface IAdaptable
 {
  /// <summary>
  /// 取得适配的接口
  /// </summary>
  /// <param name="type"></param>
  /// <returns></returns>
  object GetAdapter(Type type);
 }

/// <summary>
 /// ITreeNode 具备层级结构的接口。
 /// </summary>
 public interface ITreeNode
 { 
  /// <summary>
  /// 层次
  /// </summary>
  int TreeNodeLevel
  {
   get;
  }
  /// <summary>
  /// 编号
  /// </summary>
  int TreeNodeId
  {
   get;
  }
  /// <summary>
  /// 是否叶子节点
  /// </summary>
  bool TreeNodeIsLeaf
  {
   get;
  }
 }

/// <summary>
  /// 取得层次结构的前置符号列表
  /// </summary>
  /// <param name="list">ITreeNode接口的列表</param>
  public static IList GetTreePrefixSymbolList(IList list)
  {
   IList result = new ArrayList();
   string lastSymbol = "";
   for (int i = 0; i < list.Count; i++)
   {
    StringBuilder buf = new StringBuilder();
    if(!(list[i] is IAdaptable)) continue;
    
    ITreeNode item = (ITreeNode) ((IAdaptable)list[i]).GetAdapter(typeof(ITreeNode));
    if(item == null) continue;
    
    int min = Math.Min(lastSymbol.Length, item.TreeNodeLevel);

    if(item.TreeNodeLevel <= lastSymbol.Length)
    {
     buf.Append(lastSymbol.Substring(0,min-1));
    }
    else
    {     
     for(int j=0;j < min;j++)
     {
      if(lastSymbol[j] == '├')
       buf.Append('│');
      else if(lastSymbol[j] == '└')
       buf.Append(" "); 
      else
       buf.Append(lastSymbol[j]);
     }
     for(int j=min;j < item.TreeNodeLevel-1;j++)
     {     
      buf.Append(" ");
     }       
    }
    if(i+1 < list.Count)
    {
     if(ExistsSameLevelNextNode(list,item, i))
     {
      buf.Append("├");
     }
     else
     {
      buf.AppendFormat("└");
     }
    }
    else
     buf.AppendFormat("└");
     
    lastSymbol = buf.ToString();

    string s = buf.ToString();

    result.Add( s );
   }
   return result;
  }
  /// <summary>
  /// 判断往下的同一层次是否还有其他节点
  /// </summary>
  /// <param name="list">ITreeNode接口的列表</param>
  /// <param name="item">树节点</param>
  /// <param name="itemIndex">树节点在列表中的序号</param>
  /// <returns></returns>
  private static bool ExistsSameLevelNextNode(IList list, ITreeNode item, int itemIndex)
  {
   for(int i=itemIndex+1;i < list.Count;i++)
   {
    ITreeNode nextItem = (ITreeNode) ((IAdaptable)list[i]).GetAdapter(typeof(ITreeNode));
    if(nextItem == null) continue;

    if(nextItem.TreeNodeLevel == item.TreeNodeLevel)
     return true;
    else
    {
     if(nextItem.TreeNodeLevel < item.TreeNodeLevel) return false;
    }
   }
   return false;
  }

你可能感兴趣的:(table)