如何使用Linq查询将一个列表绑定到另一个列表中

时间:2018-06-07 07:09:37

标签: c# api wep

  public class ResponseLibraryClass
    {
        public int Response { get; set; }
        public string ErrorMessage { get; set; }
        public List<LibraryClass> lst_Library { get; set; }
        public List<AlbumClass> lst_Album { get; set; }
    }   
    public class LibraryClass
    {
        public int? LibraryId { get; set; }
        public string LibraryName { get; set; }
        public List<AlbumClass> lst_Album { get; set; }        
    }
    public class AlbumClass
    {
        public int? LibraryId { get; set; }
        public int? BookId { get; set; }
        public string BookName { get; set; }
    }

在控制器中我有这段代码:

    [System.Web.Http.AcceptVerbs("GET", "POST")]
    public ResponseLibraryClass AllLibraryData(ResponseLibraryClassobj_ClientClass)
    {
        ResponseLibraryClass Obj_Result = new ResponseLibraryClass();

        List<LibraryClass> lst_Library = new List<LibraryClass>();
        List<AlbumClass> lst_Album = new List<AlbumClass>();

        try
        {
            lst_Library = (from cm in db.Libraries                                 
                      select new LibraryClass
                      {
                          LibraryId = cm.LibraryId,
                          LibraryName = cm.LibraryName
                      }).ToList();
            Obj_Result.Response = 1;
            Obj_Result.lst_Library = lst_Library;
            foreach (var item in lst_Library)
            {
                (from a in db.Albums
                where a.LibraryId == item.LibraryId
                select new AlbumClass
                {
                    BookId = a.BookId,
                    BookName = a.BookName,
                    BookImage = a.BookImage,
                    LibraryId = a.LibraryId
                }).ToList();
            }
            Obj_Result.Response = 1;
            Obj_Result.lst_Album = lst_Album;        
        }
        catch (Exception ex)
        {
            lst_Library = null;
        }
        return Obj_Result;
    }

这会让我像这样返回json,意味着它在不同的数组中返回lst_album。

"lst_Library ": [{"LibraryId": 1,"LibraryName": "Jungle Music","lst_Album":null}]

"lst_Album": [{"LibraryId": 4,"BookId": 10,"BookName": "Level 1a",}]

由于lst_Album在lst_Library中变为null。但我想在lst_Library里面找到lst_album。 那么如何在lst_Album中插入数组。意味着我希望json以这种形式出现:

"lst_Library ": [{"LibraryId": 1,"LibraryName": "Jungle Music",
"lst_Album":  {"LibraryId": 4,"BookId": 10,"BookName": "Level 1a"}]

0 个答案:

没有答案