您可以按產品,然後組產品按類型行組行:
var query = from r in table.AsEnumerable()
group r by r.Field<int>("productid") into g
let types = g.GroupBy(r => r.Field<int>("typenumber"))
select new {
productId = g.Key,
name = GetText(types.FirstOrDefault(t => t.Key == 0)),
shortdescription = GetText(types.FirstOrDefault(t => t.Key == 2)),
longdescription = GetText(types.FirstOrDefault(t => t.Key == 1))
};
當輔助方法,只是訂單輸入行號行並返回串接文本
private static string GetText(IEnumerable<DataRow> rows)
{
if (rows == null)
return null;
var query = from r in rows
orderby r.Field<int>("linenumber")
select r.Field<string>("text");
return String.Join(" ", query);
}
輸出:
[
{
productId: 100,
name: "this is the name of a1",
shortdescription: "this is the description of a1",
longdescription: null
},
{
productId: 200,
name: "this is the name of a2",
shortdescription: null,
longdescription: "shortdescription of a2"
}
]
您可以手動構建新的DataTable或使用此方法創建新的DataTable。你也可以使用LINQ構建以XML爲xml:
var xdoc = new XDocument(new XElement("products",
from p in query
select new XElement("product",
new XAttribute("productId", p.productId),
new XElement("name", p.name),
new XElement("shortDescription", p.shortdescription),
new XElement("longDescription", p.longdescription))));
輸出:
<products>
<product productId="100">
<name>this is the name of a1</name>
<shortDescription>this is the description of a1</shortDescription>
<longDescription />
</product>
<product productId="200">
<name>this is the name of a2</name>
<shortDescription />
<longDescription>shortdescription of a2</longDescription>
</product>
</products>
或(可能)更簡單的方案 - 而不是匿名類型的使用,創造出可以很容易地序列化爲XML定製類。
到目前爲止,你有嘗試過什麼嗎?爲什麼你需要結果作爲DataTable? –
@SergeyBerezovskiy我已經嘗試過這與Foreach循環已經,但失敗。我的情況比這裏解釋的情況稍微複雜一些。這只是一個原型,這就是爲什麼我沒有在這裏分享代碼。 – Athul
@SergeyBerezovskiy實際上我希望我的XML格式的最終結果,如果我在Datatable中解決了這個問題。我很容易將它轉換爲XMLDoc。 – Athul