matt
matt

Reputation: 321

Query syntax for getting a list as a list of different types?

I have a query that fetches books, I'm new to LINQ so I don't know the syntax:

var books = (from book in db.Books
             join borrow in db.Borrows on book equals borrow.Book
             select new BookDTO { Title = book.Title, 
                                  Borrows = book.Borrows.ToList() }).ToList(); // book.Borrows.ToList() <- use dto's instead

How can I select Book.Borrows as a list of objects (BorrowDTO's)? Is there something like Borrows = new List<BorrowDTO>(book.Borrows)

Upvotes: 0

Views: 93

Answers (2)

David
David

Reputation: 218950

You can use .Select() to project the list into a different type. So instead of this:

Borrows = book.Borrows.ToList()

you would have something like this:

Borrows = book.Borrows.Select(b => new BorrowDTO { /* properties here */ }).ToList()

Note that, depending on your data source, there may be more efficient ways to approach selecting your data. If you're pulling directly from LINQ To Entities then you may run into problems trying to materialize a type within the query that isn't known to the DB, or any other operation that can't be translated into SQL. It's also not necessarily wise to toss in a bunch of .ToList() operations without a specific purpose.

But that's all theoretical at this point in the question. Based on the code shown and on LINQ syntax itself, you can select from a list just fine. (I'd even recomment using the extension method syntax more than the query syntax that you currently use. Personal preference of course, but I find it easier and more intuitive to build nested operations like this. Though you can just as well use the from ... select ... syntax after Borrows =, I would imagine.)

Upvotes: 1

Some random IT boy
Some random IT boy

Reputation: 8467

Just select book.Borrows instead of creating a new temporal object.

That query is going to return a IEnumerable of the Borrows type; and you'll be able to iterate through it and convert it into a List if you please

Upvotes: 0

Related Questions