Vya*_*Rao 2 c# linq asp.net datatable json
我正在尝试从C#datatable构建JSON输出.单个数据表也包含父级和子级.我想使用LINQ来设置JSON数据,但是我想避免创建类,因为我有很多这样的要求,并且为每个创建类将是一个负担.
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}
]}
Run Code Online (Sandbox Code Playgroud)
我试过的示例代码
//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();
Run Code Online (Sandbox Code Playgroud)
错误
Results View = The type '<>f__AnonymousType0<a>' exists in both 'APP-SERVICE.dll' and 'CommonLanguageRuntimeLibrary'
Run Code Online (Sandbox Code Playgroud)
如果可以,请提供更好的代码.提前致谢
在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);
Run Code Online (Sandbox Code Playgroud)