具有父子关系的数据表为具有层次结构的 JSON 格式

Datatable with Parent and Child to JSON format with Hierarchy

我正在尝试从 C# 数据表构建一个 JSON 输出。单个数据表也包含父项和子项。我想使用 LINQ 来设置 JSON 数据,但我想避免创建 类 因为我有很多这样的要求并且为每个要求创建 类 将是一个负担。

代码

var obj = dt.AsEnumerable()
            .GroupBy(r => r["Head"])
            .ToDictionary(g => g.Key.ToString(),
                          g => g.Select(r => new {
                                                item = r["Item"].ToString(),
                                                quantity = (int)r["Quantity"]
                                             })
                                .ToArray());

var json = JsonConvert.SerializeObject(obj);

以上代码提供了以下输出,

{
Sports : [
{item: 'Porsche 911', quantity: 100},
{item: 'Porsche 912', quantity: 200}
],
Luxury : [
{item: 'BMW 3 Series', quantity: 300}
],
Small :[
{item: 'Toyota Corolla', quantity: 400},
{item: 'Mitsubishi Lancer', quantity: 500},
{item: 'Mitsubishi Lancer 2', quantity: 600}
]}

但我想要以下输出

[
    {
        Head: 'Sports',
        total: 300,
        data : [
            {item: 'Porsche 911', quantity: 100},
            {item: 'Porsche 912', quantity: 200}
        ]
    },
    {
        Head: 'Luxury',
        total: 300,
        data : [
        {item: 'BMW 3 Series', quantity: 300}
        ]
    },
    {
        Head: 'Small',
        total: 1500,
        data :[
            {item: 'Toyota Corolla', quantity: 400},
            {item: 'Mitsubishi Lancer', quantity: 500},
            {item: 'Mitsubishi Lancer 2', quantity: 600}
        ]
    }
]

此 post 是 的副本。我想要不同格式的数据。

可以这样写:

var obj = dt.AsEnumerable()
            .GroupBy(r => r["Head"])
            .Select(g => new
            {
                Head = g.Key.ToString(),
                total = g.Sum(x => (int)x["Quantity"]),
                data = g.Select(r => new
                {
                    item = r["Item"].ToString(),
                    quantity = (int)r["Quantity"]
                }).ToArray()
            })
            .ToList();


var json = JsonConvert.SerializeObject(obj);