ลองดูตัวอย่างที่ผมทดลองเขียนขึ้นมาดูนะครับ ผมยังไม่ได้ทดสอบจริง แต่คิดว่าน่าจะใช้ได้นะ
using System.Data;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
DataTable table = new DataTable();
// TODO: สมมติว่าคุณได้ทำการดึงข้อมูลมาจากฐานข้อมูลมาเก็บไว้ที่ table เรียบร้อยแล้ว
Dictionary<int, Node> nodes = new Dictionary<int, Node>();
DataView view = new DataView(table);
view.RowFilter = "parent_id=0"; // 0 หมายถึง Node แรก
int rootId = (int)view[0]["ID"];
Node rootNode = CreateNode(table, nodes, rootId);
}
static Node CreateNode(DataTable table, Dictionary<int, Node> nodes, int id)
{
DataView view = new DataView(table);
view.RowFilter = "ID=" + id.ToString();
string data = view[0]["DATA"].ToString();
int parentId = (int)view[0]["parent_id"]; // 0 หมายถึง Node แรก
int leftChildId = (int)view[0]["L_childid"]; // 0 หมายถึง ตัวสุดท้าย
int rightChildId = (int)view[0]["R_childid"]; // 0 หมายถึง ตัวสุดท้าย
Node node = new Node();
nodes.Add(id, node);
node.id = id;
node.data = data;
if (parentId == 0) node.parentNode = null;
else if (nodes[parentId] != null) node.parentNode = nodes[parentId];
else node.parentNode = CreateNode(table, nodes, parentId);
if (leftChildId == 0) node.leftChildNode = null;
else if (nodes[leftChildId] != null) node.leftChildNode = nodes[leftChildId];
else node.leftChildNode = CreateNode(table, nodes, leftChildId);
if (rightChildId == 0) node.rightChildNode = null;
else if (nodes[rightChildId] != null) node.rightChildNode = nodes[rightChildId];
else node.rightChildNode = CreateNode(table, nodes, rightChildId);
return node;
}
}
class Node
{
public int id;
public string data;
public Node parentNode;
public Node leftChildNode;
public Node rightChildNode;
}
Imagination is more Important than Knowledge... /A.Einstein