1
我正在創建一個XElement
對象,並且在使用Linq將多個元素添加到節點時遇到問題。Linq to XElement,多個參數
有對象的多個屬性的列表:
class Point { int x; int y; ... }
List<Point> Points = new List<Point>()
{
new Point(1,2),
new Point(3,4)
};
我想這個列表轉換爲使用單獨的構造平坦XElement
(一次性)。
我希望看到的:
<Points>
<x>1</x>
<y>2</y>
<x>3</x>
<y>4</y>
</Points>
我走到這一步,最遠:
new XElement("Points",
Points.Select(a => new {
X = new XElement("x", a.x),
Y = new XElement("y", a.y)
});
其產生的嵌套列表,解析爲一個單一的XElement
。
<Points>{ X = <x>1</x>, Y = <y>2</y> }{ X = <x>3</x>, Y = <y>4</y> }</Points>
(我需要保存的順序,以便聯合將無法正常工作)
我想要做的一切在構造函數中,像上面,並且不想手動加點,像這樣:
XElement PointsXml = new XElement("Points");
foreach (var item in Points)
{
PointsXml.Add(item.x);
PointsXml.Add(item.y);
}
工作就像一個魅力,非常感謝!另外,'Points.Select(a => new [] ...'也起作用。 – user5226582