数据表与父母子女JSON格式

编程入门 行业动态 更新时间:2024-10-14 22:19:26
本文介绍了数据表与父母子女JSON格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图建立从C#DataTable中的一个输出JSON。单DataTable包含家长和孩子为好。我想使用LINQ来设置JSON数据,但想避免创建类,因为我对每个很多这样的要求和创建类将是一个负担。

I am trying to build a JSON output from the C# datatable. The single datatable contains parent and child as well. I would like to use LINQ to setup the JSON data, but would like to avoid creating classes since I have many such requirements and creating classes for each will be a burden.

的JSON输出应为

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

样code我试图

Sample code I tried

//get current stock DataTable dtCurrentStock = inventoryReports.getCurrentStock(currentDate); //get distinct item group DataTable dtItemGroup = dtCurrentStock.DefaultView.ToTable(true, "HEAD"); DataSet sd = new DataSet(); var itemGroup = dtItemGroup.AsEnumerable(); var items = dtCurrentStock.AsEnumerable(); var result = itemGroup.Select(group => new { groupName = group.Field<string>("HEAD"), itemDetl = items. Where(item => (item.Field<string>("HEAD") == group.Field<string>("HEAD"))). Select(detl => new { a = detl.ToString() })//.ToList() }).ToList();

错误

Results View = The type '<>f__AnonymousType0<a>' exists in both 'APP-SERVICE.dll' and 'CommonLanguageRuntimeLibrary'

请提供一个更好的code(如果可用)。在此先感谢

Please provide a better code if available. Thanks in advance

推荐答案

使用LINQ的帮助

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

更多推荐

数据表与父母子女JSON格式

本文发布于:2023-10-28 03:59:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1535451.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据表   子女   父母   格式   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!