c# - 如何将记录存储到可枚举模型列表中的字符串数组中
问题描述
我正在尝试将记录列表存储为给定格式的字符串数组。我已经给出了布局的格式,数据需要存储在字符串数组 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'
}
]
}
];
为此,我有三个模型
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
在存储库类
public IEnumerable<DepotDepartmentLink> GetAllDepotDepartmentLink()
{
return _db.DepotDepartmentLink.Include(m => m.Depot).Include(m=>m.Department);
}
在控制器中,我试图将数据结果放入数组 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);
推荐阅读
- node.js - 在 nodejs 客户端/服务器中通过 TCP 发送查询结果的问题
- xml - 现有代码中的大写集成 (XSLT 1.0)
- javascript - ReactJs - 在 li 元素上的单击事件上,不会立即添加该类
- swift - SwiftUI Core Data Master/Detail
- ruby - Ruby 命名空间与在方法中定义并使用 attr 的模块类实例变量冲突:
- java - 如何让一个被发现为真的方法在下面显示另一个方法?爪哇
- c# - 如何对以下意外事件进行编程?
- c++ - C++ 中的异或加密
- c# - 使用 Blazor 服务器端组件的 MVC 应用程序中的防伪令牌验证
- rust - 为什么这里会出现 Rust 可变借用?