C# 如何将记录从可枚举模型列表存储到字符串数组中
我试图将记录列表按给定格式存储到字符串数组中。我已经给出了布局的格式,因为给定的数据需要存储在字符串数组myData中 为此,我有三个模型C# 如何将记录从可枚举模型列表存储到字符串数组中,c#,json,asp.net-core,C#,Json,Asp.net Core,我试图将记录列表按给定格式存储到字符串数组中。我已经给出了布局的格式,因为给定的数据需要存储在字符串数组myData中 为此,我有三个模型 public class Depot { public int Id { get; set; } public string DepoName { get; set; } } public class Department { public int Id { get; set; }
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; }
}
在存储库类中
public IEnumerable<DepotDepartmentLink> GetAllDepotDepartmentLink()
{
return _db.DepotDepartmentLink.Include(m => m.Depot).Include(m=>m.Department);
}
public IEnumerable 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();
}
public IActionResult Index()
{
IEnumerable DepotDepartDepartment=_DepotDepartDepartmentLinkRepo.GetAllDepotDepartDepartmentLink();
字符串myData=“[]”;
myData=“[”+string.Join(“,”,depotdepartment.Select(l=>l.DepotId+”+l.DepartmentId.ToArray());
返回视图();
}
这是一个简单的数据分组。它使用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);
您是否尝试使用JSON序列化?要转换为JSON sting数组,无论是要在视图中显示的对象还是其他对象,都必须序列化添加引用newtonsoft和类似字符串jstr=JsonConvert.SerializedObject(depotdepartment,Formatting.Indented);请您根据我的示例指导我如何转换为json字符串arrayChetan,我按照您的建议进行了尝试,但不起作用。因为字符串数组应以与上面所附格式相同的格式传递,并且
DepotDepartmentLink
包含。。。?
public IActionResult Index()
{
IEnumerable<DepotDepartmentLink> depotdepartment = _depotDepartmentLinkRepo.GetAllDepotDepartmentLink();
string myData = "[]";
myData = "[" + string.Join(",",depotdepartment.Select(l => l.DepotId + "." + l.DepartmentId).ToArray());
return View();
}
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);