首页 > 解决方案 > 如何将记录存储到可枚举模型列表中的字符串数组中

问题描述

我正在尝试将记录列表存储为给定格式的字符串数组。我已经给出了布局的格式,数据需要存储在字符串数组 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();
   }

标签: c#jsonasp.net-core

解决方案


这是一个简单的数据分组。它是使用 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);

推荐阅读