Search code examples
.netvb.netlinq.net-3.5windows-ce

How to get the number of items in a collection using LINQ


I don't know my question title is correct for my situation. Below is my issue. The following are my classes.

Public Class Employee
public  Name As String
public  ID as String
public  SaleDivs as List(of SalesDivision)
End Class 

Public Class SalesDivision
public  Name As String
public  ID as String
public  SaleLocations as List(of SaleLocation)
End Class

Public Class SaleLocation
public  Name As String
public  ID as String
End Class

I have a list of Employess. In that list a sales location can be assigned to multiple employees and an employee can have multiple sales location.

How I find the number of employees assigned for a particular sale location using Linq.

I am using .NET CE Framework 3.5.

Thanks in advance.


Solution

  • You can use multiple From clauses (a.k.a. SelectMany).

    Given the following example data:

    Dim loc1 = New SaleLocation With { .Name = "Location1" }    
    Dim loc2 = New SaleLocation With { .Name = "Location2" }    
    Dim div1 = New SalesDivision With { .Name = "Div1", .SaleLocations = New List(Of  SaleLocation) From { loc1 }}
    Dim div2 = New SalesDivision With { .Name = "Div2", .SaleLocations = New List(Of  SaleLocation) From { loc2 }}
    Dim div3 = New SalesDivision With { .Name = "Div3", .SaleLocations = New List(Of  SaleLocation) From { loc1, loc2 }}
    
    Dim emp1 = New Employee With { .Name = "Harry", .SaleDivs = New List(Of SalesDivision) From { div1 }}
    Dim emp2 = New Employee With { .Name = "Marry", .SaleDivs = New List(Of SalesDivision) From { div2 }}
    Dim emp3 = New Employee With { .Name = "Larry", .SaleDivs = New List(Of SalesDivision) From { div3 }}
    
    Dim employees = New List(Of Employee) From { emp1, emp2, emp3 }
    

    you can use the following query:

    Dim result = From employee in employees
                 From division in employee.SaleDivs
                 From location in division.SaleLocations
                 Where location.Name = "Location2"
                 Select employee Distinct
    

    and to get the count:

    Dim numberOfLocation2Employees = result.Count()
    

    In your real code you probably use the ID field instead of Name.