Tom
Tom

Reputation: 1071

VB.NET LINQ - Count of collection within collection?

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?

Upvotes: 3

Views: 2116

Answers (2)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112527

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.

Upvotes: 2

BrokenGlass
BrokenGlass

Reputation: 160942

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)

Upvotes: 6

Related Questions