从表中获取父/子关系

时间:2014-05-08 09:57:19

标签: c#

说我们有下表

PNLId   PNLCode PNLParentId Operator    Sign
0       0   ~   S
49  C   51  +   NULL
50  Z   51  +   NULL
51  Y   107 /   NULL
52  B   107 /   NULL
53  B   108 +   NULL

我定义了以下类Node来获取父/子

的关系
class Node
{
    public int Id { get; set; }
    public int? ParentId { get; set; }
    public string Operator { get; set; }
    public string Sign { get; set; }
    public Node Parent { get; set; }
    public IList<Node> Children { get; set; }

    public Node()
    {
        Children = new List<Node>();
    }

    public override string ToString()
    {
        //return "Node: " + Operator + " " + Id + " " + string.Join(",", Children.Select(x => x.Id));
        return "Node: " + Operator + " " + Id + " " + 
               string.Join(",", Children.Select(x => string.Format("({0}, {1})", x.Sign, x.Id)));
    }
}

var map = new Dictionary<int, Node>();
var rootNodes = new List<Node>();

foreach (DataRow row in dt.Rows)
{
    int id = Convert.ToInt32(row["PNLId"]);
    int? parentId = null;
    if (!row.IsNull("PNLParentId"))
    {
        parentId = Convert.ToInt32(row["PNLParentId"]);
    }
    string op = Convert.ToString(row["Operator"]);
    string sign = Convert.ToString(row["Sign"]);
    map[id] = new Node
    {
        Id = id,
        ParentId = parentId,
        Operator = op,
        Sign=sign

    };
}

知道如何完成上面的代码以正确理解父/子的关系吗?任何帮助都是最受欢迎的!

0 个答案:

没有答案