我正在尝试使用一些节点和边创建一个json数据。
{"nodes":[
{"id":0,"title":"a","x":1200,"y":50},
{"id":1,"title":"b","x":800,"y":200},
{"id":2,"title":"c","x":1200,"y":200},
{"id":3,"title":"d","x":1200,"y":400},
{"id":4,"title":"e","x":800,"y":400},
{"id":5,"title":"f","x":1000,"y":500}],
"edges":[
{"source":0,"target":2},
{"source":1,"target":3},
{"source":2,"target":3},
{"source":1,"target":4},
{"source":2,"target":4},
{"source":3,"target":5},
{"source":4,"target":5}]
}
我已经硬编码了" x"和" y"价值观。我想生成那些" x"和" y"值使得相同深度的节点保持在相同的水平。在对值进行硬编码之前,我使用以下方法生成这些值:
strJosn.Append("{\"id\":" + i + ",\"title\":\"" + nodeNames[i] + "\",\"x\":" + GetRandomNumber(arlRandom) + ",\"y\":" + GetRandomNumber(arlRandom));
我的csv数据如下所示:
第一列上方的表示子列,第二列表示第一列,它是第一列中子节点的父节点。 相应的树看起来像这样。
如何生成这些值,以便我将节点对齐到如图所示的相同级别?
修改 我已将csv数据存储在dataTable中。
答案 0 :(得分:1)
我已经创建了一个班级Node
,但这并不完美,但效果很好:
internal class Node
{
public Node Parent { get; set; }
private Node m_child;
public Node Child
{
get { return m_child; }
set
{
m_child = value;
value.Parent = this;
}
}
public int Id { get; set; }
public string Title { get; set; }
}
internal class Program
{
static void Main(string[] args)
{
Dictionary<int, Node> nodes = new Dictionary<int, Node>()
{
{0, new Node() {Id = 0, Title = "a"}},
{1, new Node() {Id = 1, Title = "b"}},
{2, new Node() {Id = 2, Title = "c"}},
{3, new Node() {Id = 3, Title = "d"}},
{4, new Node() {Id = 4, Title = "e"}},
{5, new Node() {Id = 5, Title = "f"}}
};
nodes[0].Child = nodes[2];
nodes[1].Child = nodes[3];
nodes[2].Child = nodes[3];
nodes[1].Child = nodes[4];
nodes[2].Child = nodes[4];
nodes[3].Child = nodes[5];
nodes[4].Child = nodes[5];
Dictionary<int, List<Node>> nbParentNodesDictionary = new Dictionary<int, List<Node>>();
foreach (KeyValuePair<int, Node> valuePair in nodes)
{
Node parent = valuePair.Value.Parent;
int nbOfParent = 0;
while (parent != null)
{
nbOfParent++;
parent = parent.Parent;
}
if (!nbParentNodesDictionary.ContainsKey(nbOfParent))
{
nbParentNodesDictionary[nbOfParent] = new List<Node>();
}
nbParentNodesDictionary[nbOfParent].Add(valuePair.Value);
}
const int yOffSet = 100;
foreach (KeyValuePair<int, List<Node>> keyValuePair in nbParentNodesDictionary)
{
const int xMax = 500;
int xOffset = xMax/(keyValuePair.Value.Count+1);
int x = 0;
foreach (Node node in keyValuePair.Value)
{
x += xOffset ;
Console.Out.WriteLine("id:" + node.Id + " title:" + node.Title + " x:" + x + " y:" + yOffSet * keyValuePair.Key);
}
}
}
}
哪个输出:
id:0 title:a x:166 y:0
id:1 title:b x:332 y:0
id:2 title:c x:250 y:100
id:3 title:d x:166 y:200
id:4 title:e x:332 y:200
id:5 title:f x:250 y:300