C# 从表中获取父/子关系

C# 从表中获取父/子关系,c#,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 我定义下面的类节点来获取父/子关系 class Node { public int Id { get; set; } public

假设我们有下表

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
我定义下面的类节点来获取父/子关系

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

    };
}
类节点
{
公共int Id{get;set;}
public int?ParentId{get;set;}
公共字符串运算符{get;set;}
公共字符串符号{get;set;}
公共节点父节点{get;set;}
公共IList子项{get;set;}
公共节点()
{
Children=新列表();
}
公共重写字符串ToString()
{
//返回“Node:”+Operator+“”+Id+“”+string.Join(“,”,Children.Select(x=>x.Id));
返回“节点:”+运算符+“”+Id+“””
Join(“,”,Children.Select(x=>string.Format(({0},{1})”,x.Sign,x.Id));
}
}
var map=newdictionary();
var rootNodes=新列表();
foreach(数据行中的数据行)
{
int id=Convert.ToInt32(第[“PNLId”行]);
int?parentId=null;
如果(!row.IsNull(“PNLParentId”))
{
parentId=Convert.ToInt32(第[“PNLParentId”行]);
}
字符串op=Convert.ToString(行[“运算符”]);
字符串符号=Convert.ToString(行[“符号]);
map[id]=新节点
{
Id=Id,
ParentId=ParentId,
操作员=op,
符号
};
}
你知道如何完成上面的代码以正确地获得父子关系吗?任何帮助都将不胜感激

可能重复的