简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM