您好我有以下格式的数据集:
NodeID | NodeName | NodeAttribute1 | NodeAttribute2
1 | n1 | 1 | null
2 | n2 | 1 | null
3 | n3 | 1 | 1
4 | n4 | 2 | 2
5 | n5 | 2 | 3
6 | n6 | 2 | 4
基本上,属性确定虚拟树中节点的位置。我希望结果看起来像这样:
<NodeTree>
<ParentNodeType1 NodeAttribute1 = 1>
<node name="n1" nodeID=1>
<node name="n2" nodeID=2>
<ParentNodeType2 NodeAttribute2 = 1>
<node name = "n3" nodeID = 3>
</ParentNodeType2>
</ParentNodeType1>
<ParentNodeType1 NodeAttribute1 = 2>
<ParentNodeType2 NodeAttribute2 = 3>
<node name = "n4" nodeID=4>
</ParentNodeType2>
<ParentNodeType2 NodeAttribute2 = 4>
<node name = "n5" nodeID=5>
<node name = "n6" nodeID=6>
</ParentNodeType2>
</ParentNodeType1>
</NodeTree>
因此n1和n2在parent1中,但是n3更深一级,因为第二个属性不为null。任何人都有任何关于如何使用linq或类似的东西进行思考的想法?
答案 0 :(得分:1)
抱歉,我试图理解这一点,但我失败了。
你的数据似乎没有很好地描述(有什么属性?为什么你不想在XML中映射层次结构?什么是ParentNodeType1 / 2应该是什么?NodeAttribute2似乎是父节点ID但是在XML节点中,n5和n6都在<ParentNodeType2 NodeAttribute2 = 4>
之下,我不够聪明,无法检测那里的逻辑:)
尽管如此,为了帮助你,这就是我认为会有用的东西,你可以根据自己的“要求”调整它,而不必了解它(眨眼间眨眼)< / p>
using System;
using System.Xml.Linq;
using System.Linq;
using System.Collections.Generic;
namespace X
{
static class Y
{
public static int Main(string[] args)
{
var data = new Record[] {
new Record(1, "n1", 1, null),
new Record(2, "n2", 1, null),
new Record(3, "n3", 1, 1),
new Record(4, "n4", 2, 2),
new Record(5, "n5", 2, 3),
new Record(6, "n6", 2, 4),
};
Func<Record, XElement> subtree;
subtree = node => new XElement("node",
new XAttribute("name", node.NodeName),
new XAttribute("nodeID", node.NodeID),
new XAttribute("NodeAttribute1", node.NodeAttribute1),
data.ChildrenOf(node.NodeID).Select(subtree));
XElement xml = new XElement("NodeTree",
data.Where(root => root.NodeAttribute2 == null)
.Select(subtree));
Console.WriteLine(xml);
return 0;
}
struct Record
{
public readonly int NodeID;
public readonly string NodeName;
public readonly int NodeAttribute1; //level?
public readonly int? NodeAttribute2; //parent
internal Record(int id, string name, int at1, int? at2)
{
NodeID = id;
NodeName = name;
NodeAttribute1 = at1;
NodeAttribute2 = at2;
}
}
private static IEnumerable<Record> ChildrenOf(this IEnumerable<Record> data, int? parentId)
{
return data.Where(child => child.NodeAttribute2 == parentId);
}
}
}
哦,以防万一,这是输出
<NodeTree>
<node name="n1" nodeID="1" NodeAttribute1="1">
<node name="n3" nodeID="3" NodeAttribute1="1">
<node name="n5" nodeID="5" NodeAttribute1="2" />
</node>
</node>
<node name="n2" nodeID="2" NodeAttribute1="1">
<node name="n4" nodeID="4" NodeAttribute1="2">
<node name="n6" nodeID="6" NodeAttribute1="2" />
</node>
</node>
</NodeTree>