linq,计算counts的个数

linq, calculating the count of counts

我想知道我是否有一个对象列表,这些对象有自己的对象列表,如何获得总数。例如:

public class FileWrapper {
   List<File> Files
}

public class File {
   ...
}

那么对于 List 包装器,我如何获得文件的总数。

wrappers.ForEach(f => f.Files.Count).Count()

您想 Sum 每个列表的计数,而不是 Count 每个列表的计数:

var sum = wrappers.Sum(file => file.Files.Count);
wrappers.Select(f => f.Files.Count).Sum()

您也可以使用 SelectMany

var sum = wrappers.SelectMany(wrapper => wrapper.Files).Count();

我无法访问 VS。所以它是眼睛编译的。

正如@Servy 所说,这是个坏主意:

This forces every single inner list to be iterated to determine its count, when they're capable of just returning the already-known Count.