VB.NET LINQ - counting a collection in a collection?
Run the following script:
Public Class Store
Public Overridable Property Areas As List(Of Area)
End Class
Public Class Area
Public Overridable Property Shelves As List(Of Shelf)
End Class
Public Class Shelf
Public Property ID as integer
End Class
What's the fastest way to get total store shelves? That is, for the store, I get the total number of areas using Areas.Count
Or do I have to go through each area and count the number of shelves?
+3
source to share
2 answers
In C #:
int count = Store.Areas.SelectMany(x => x.Shelves).Count();
Converted to VB:
Dim count = Store.Areas.SelectMany(Function(x) x.Shelves).Count()
(using an online converter , not a VB guy)
+5
source to share
Use this LINQ expression
Dim count As Integer = store.Areas.Sum(Function(a) a.Shelves.Count())
Note that this is different from @ BrokenGlass answer. It first aligns the nested collections with SelectMany
, and then counts the total of the resulting elements, i.e. It iterates over the total number of items. Where when I just iterate over the outer collection and summarize the property of the Count
inner collection. It should be much faster.
+2
source to share