LINQ: several levels

Imagine a library containing many books containing many pages. I have a Library object in which there is a HashSet of books that have a list of page objects. How can I use LINQ to calculate how many pages are in the library?

Greetings

Nick

+3
source share
3 answers

Assuming the types you describe look something like this:

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

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

There are several ways to write such a request.

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 are many ways you can articulate this. Personally, I would write it using the first method.

+8
source
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();
+2
source
var count = library.books.Sum(x=>x.pages.Count())
+1
source

Source: https://habr.com/ru/post/1783367/


All Articles