[英]How can I store the record into string array from Enumerable model list
我正在嘗試將記錄列表存儲為給定格式的字符串數組。 我已經給出了布局的格式,因為數據需要存儲在字符串數組 myData字符串數組格式鏈接中
var myData = [
{
id: 1,
title: 'Depot 1 ',
subs: [
{
id: 1.1,
title: 'Depot 1.Admin'
},
{
id: 1.2,
title: 'Depot 1.Accounts'
},
]
},
{
id: 2,
title: 'Depot 2',
subs: [
{
id: 2.1,
title: 'Depot 2.Admin'
}, {
id: 2.2,
title: 'Depot 2.Accounts'
}, {
id: 2.3,
title: 'Depot 2.Sales'
}
]
}
];
為此,我有三個 model
public class Depot
{
public int Id { get; set; }
public string DepoName { get; set; }
}
public class Department
{
public int Id { get; set; }
public string DepartmentName { get; set; }
}
public class DepotDepartmentLink
{
public int Id { get; set; }
public int DepotId { get; set; }
public int DepartmentId { get; set; }
public Depot Depot { get; set; }
public Department Department { get; set; }
}
Depot contains the record
Id =1 , Depotname = Depot 1
Id =2 , Depotname = Depot 2
Department contains the record
Id =1 , Departmentname = Admin
Id =2 , Departmentname = Accounts
Id =3 , Departmentname = Sales
Departmentlink contains
Depotid = 1 DepartmentId = 1
Depotid = 1 DepartmentId = 2
Depotid = 2 DepartmentId = 1
Depotid = 2 DepartmentId = 2
Depotid = 2 DepartmentId = 3
在存儲庫 class
public IEnumerable<DepotDepartmentLink> GetAllDepotDepartmentLink()
{
return _db.DepotDepartmentLink.Include(m => m.Depot).Include(m=>m.Department);
}
在 controller 中,我試圖將數據結果放入數組 myData 中,如上面給定的格式。 請幫忙
public IActionResult Index()
{
IEnumerable<DepotDepartmentLink> depotdepartment = _depotDepartmentLinkRepo.GetAllDepotDepartmentLink();
string myData = "[]";
myData = "[" + string.Join(",",depotdepartment.Select(l => l.DepotId + "." + l.DepartmentId).ToArray());
return View();
}
這是一個簡單的數據分組。 它是使用 LINQ 完成的。
然后我們使用任何串行器得到 json。
var result = depotdepartment
.GroupBy(dd => new { dd.DepotId, dd.Depot.DepoName })
.Select(g => new
{
id = g.Key.DepotId,
title = g.Key.DepoName,
subs = g.Select(dd => new
{
id = dd.DepotId + "." + dd.DepartmentId,
title = dd.Depot.DepoName + "." + dd.Department.DepartmentName
})
});
string json = JsonConvert.SerializeObject(result, Formatting.Indented);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.