Choose only one child from each parent

One Authorcan have a lot Book. In the table Bookthere Author_Id.

I need a LINQ query that returns IQueryable<Book>(so I can navigate using Book.Author.Nameand stuff), but only 1 book for the author.

How to do this with LINQ?

+3
source share
2 answers

Pretty precisely this:

var books = from a in authors
            from b in a.Books.Take(1)
            select b);

Edit: A less hacky way to do this:

var books = authors.Select(author => author.Books.First())
                   .Select(book => book);
+4
source
var authorsWithFirstBook = 
    from book in Books
    group book by book.Author into authorBooks
    select authorBooks.First();

This should give you the first book in the group.

Then you can perform

foreach (var book in authorsWithFirstBook) {

  Console.WriteLine(book.Author.FirstName);
}
+3
source

All Articles