本文介绍了数据表与父母子女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格式
发布评论