2

我不知道我的问题标题是否适合我的情况。下面是我的问题。以下是我的课。

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

我有一个清单Employess。在该列表中,一个销售地点可以分配给多个员工,一个员工可以有多个销售地点。

我如何使用 Linq 找到分配给特定销售地点的员工人数。

我正在使用 .NET CE 框架 3.5。

提前致谢。

4

1 回答 1

2

您可以使用多个From子句(aka SelectMany)。

给定以下示例数据:

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 }

您可以使用以下查询:

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

并得到计数:

Dim numberOfLocation2Employees = result.Count()

在您的真实代码中,您可能使用该ID字段而不是Name.

于 2013-09-19T07:19:46.273 回答