Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ: multiple levels

Tags:

c#

linq

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

like image 204
niklassaers Avatar asked Dec 21 '22 19:12

niklassaers


1 Answers

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.

like image 164
Jeff Mercado Avatar answered Jan 06 '23 06:01

Jeff Mercado