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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With