VB.NET LINQ - Count of collection within collection?

Go To StackoverFlow.com

3

Take the following scenario:

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 quickest way to get a total count of shelves for a store? I.e. for a store I get the total count of areas by using Areas.Count

Or will I need to loop through each area and tally the count of shelves?

2012-04-05 14:49
by Tom


5

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)

2012-04-05 14:52
by BrokenGlass
Awesome stuff, exactly what I wanted. Thanks for the speedy response - Tom 2012-04-05 14:56


2

Use this LINQ expression

Dim count As Integer = store.Areas.Sum(Function(a) a.Shelves.Count())

Note that this is different from @BrokenGlass' answer. He first flattens the nested collections with SelectMany and then counts the total number of resulting items, i.e. he loops over the total number of items. Where as I only loop over the outer collection and sum the Count property of the inner collection. This should be much faster.

2012-04-05 15:03
by Olivier Jacot-Descombes
Thanks Oliver, this also works - Tom 2012-04-05 15:08
Ads