niklassaers
niklassaers

Reputation: 8810

LINQ: multiple levels

Imagine that a library contains many books that have many pages. I've got the Library object, which has a HashSet of books, that have a List of page objects. How can I, using LINQ, calculate how many pages there are in the library?

Cheers

Nik

Upvotes: 4

Views: 3205

Answers (3)

ulrichb
ulrichb

Reputation: 20054

var count = library.Books.SelectMany(book => book.Pages).Count();

or equivalent:

var count2 = (from book in library.Books
              from page in book.Pages
              select page).Count();

Upvotes: 2

Jeff Mercado
Jeff Mercado

Reputation: 134901

Assuming that the types as you describe are something like this:

class Library
{
    public HashSet<Book> Books { get; }
}

class Book
{
    public List<Page> Pages { get; }
}

There are a number of ways in which you can write such a query.

Library lib = ...;

var count1 = lib.Books.Sum(b => b.Pages.Count);
var count2 = lib.Books.Select(b => b.Pages.Count).Sum();
var count3 = lib.Books.Aggregate((sum, book) => sum + book.Pages.Count);
// etc.

Of course there's many ways in which you can formulate this. Personally I'd write it using the first method.

Upvotes: 8

Saeed Amiri
Saeed Amiri

Reputation: 22555

var count = library.books.Sum(x=>x.pages.Count())

Upvotes: 1

Related Questions