带父级和子级的数据表与层次结构的JSON格式

问题描述:

我想从C#数据表生成JSON输出。单个数据表也包含父级和子级。我想使用LINQ来设置JSON数据,但是想避免创建类,因为我有很多这样的需求,并且为每个类创建类都是一个负担。带父级和子级的数据表与层次结构的JSON格式

enter image description here

代码

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} 
     ] 
    } 
] 

这篇文章是从Datatable with Parent and Child to JSON format复制。我想以不同格式的数据。

可以这样写:

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); 
+1

非常感谢您!学习LINQ的时间 –