Vitor Reis
Vitor Reis

Reputation: 989

Select only 1 child from each parent

One Author can have many Book. Table Book have Author_Id on it.

I Want a LINQ query that returns a IQueryable<Book> (So I can navigate with Book.Author.Name and stuff), but Only 1 Book per Author.

How do I do that with a LINQ?

Upvotes: 3

Views: 109

Answers (2)

aligray
aligray

Reputation: 2832

Pretty sure this is it:

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

Edit: Less hacky way to do this:

var books = authors.Select(author => author.Books.First())
                   .Select(book => book);

Upvotes: 4

Razor
Razor

Reputation: 17498

var authorsWithFirstBook = 
    from book in Books
    group book by book.Author into authorBooks
    select authorBooks.First();

That should give you the first book in the group.

You should then be able to do

foreach (var book in authorsWithFirstBook) {

  Console.WriteLine(book.Author.FirstName);
}

Upvotes: 3

Related Questions