How to translate IQueryable to List of a Custom Class?

This question is based on a [email protected] MVC Application.

I have the following function which should return a List of some class I made. Does anyone know how I can translate the IQueryable to a list? I have tried ToList(). But it still gives me a convert error.

Cannot implicitly convert type ‘System.Collections.Generic.List<>’ to ‘Model.Book[]’ [firstChance-2nd-attempt]csharp(CS0029)

LibraryController.cs

        [HttpGet("GetAuthorsAndBooks")]
        public AuthorBooks[] GetAuthorsAndBooks()
        {
            //TODO 6: missing code 1pt
            var authorsAndBooks = (
              from a in _context.Authors
              let bookList = (
                from ba in _context.BookAuthor
                where ba.AuthorId == a.Id
                join b in _context.Books on ba.BookId equals b.Id
                select new { Id = b.Id, Title = b.Title, Year = b.Year }
              )
              select new AuthorBooks { Author = a, Books = bookList.ToList() }
            );

            return authorsAndBooks; // ! CONVERT ERROR
        }
        public class AuthorBooks
        {
            public Author Author { get; set; }
            public Book[] Books { get; set; }
        }

Thanks to @Phong it works. See the modified LibraryController.cs below.

LibraryController.cs [solution]

        [HttpGet("GetAuthorsAndBooks")]
        public AuthorBooks[] GetAuthorsAndBooks()
        {
            //TODO 6: missing code 1pt
            var authorsAndBooks = (
              from a in _context.Authors
              let bookList = (
                from ba in _context.BookAuthor
                where ba.AuthorId == a.Id
                join b in _context.Books on ba.BookId equals b.Id
                select new Book { Id = b.Id, Title = b.Title, Year = b.Year }
              )
              select new AuthorBooks { Author = a, Books = bookList.ToArray() }
            ).ToArray();

            return authorsAndBooks;
        }
        public class AuthorBooks
        {
            public Author Author { get; set; }
            public Book[] Books { get; set; }
        }

Answer

You have 2 ways to get rid of the error

  • Declare List instead of Array type

    public class AuthorBooks
    {
        public Author Author { get; set; }
        public List<Book> Books { get; set; }
    }
    
  • Books = bookList.ToArray() instead.

Updated

You are selecting anonymous type at here

select new { Id = b.Id, Title = b.Title, Year = b.Year }

So you should select new Book instead, Like this

select new Book { Id = b.Id, Title = b.Title, Year = b.Year }

Leave a Reply

Your email address will not be published. Required fields are marked *