简体   繁体   English

LINQ:多个级别

[英]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. 我有一个Library对象,它有一个HashSet书籍,有一个页面对象列表。 How can I, using LINQ, calculate how many pages there are in the library? 我如何使用LINQ计算库中有多少页?

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())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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