Linq - 从子集合中选择单个项目

Phi*_*ray 2 .net linq vb.net entity-framework

我有一个父子集合对象,想知道如何使用 Linq 从子集合中获取单个项目

家长收藏

Public Class FaultCodeModel

    Public Property ID As Short
    Public Property Description As String
    Public Property FaultCodeDetails As List(Of FaultCodeDetailModel)

End Class
Run Code Online (Sandbox Code Playgroud)

儿童系列

Public Class FaultCodeDetailModel

    Public Property ID As Short
    Public Property Description As String
    Public Property NotifyPurchasing As Boolean
    Public Property NotifyPurchasingAfterHits As Short
    Public Property NotifyExpediting As Boolean
    Public Property NotifyExpeditingAfterHits As Short
    Public Property NotifyBuyer As Boolean
    Public Property NotifyBuyerAfterHits As Short
    Public Property NotifySupplier As Boolean
    Public Property NotifySupplierAfterHits As Short
    Public Property NotiifyProPack As Boolean
    Public Property NotiifyProPackAfterHits As Short
    Public Property NotifyGoodsInTeamLeader As Boolean
    Public Property NotifyGoodsInTeamLeaderAfterHits As Short

End Class
Run Code Online (Sandbox Code Playgroud)

我尝试了下面的 Linq 查询,但它返回多个父 ID 字段匹配的子项目。

Dim var = From fcd In FaultCodes Where fcd.FaultCodeDetails.Any(Function(w) w.ID.Equals(faultCodeDetailID))
            Select fcd.FaultCodeDetails
Run Code Online (Sandbox Code Playgroud)

如何从子集合中获取单个项目?

Dan*_*rth 5

我想你想要这个:

FaultCodes.SelectMany(Function(w) w.FaultCodeDetails)
          .Where(Function(w) w.ID.Equals(faultCodeDetailID))
Run Code Online (Sandbox Code Playgroud)

ID这将返回所有等于 的子项faultCodeDetailID

(我是C#人,可能VB.NET语法有点不对,请自行更正)


C# 版本:

FaultCodes.SelectMany(x => x.FaultCodeDetails)
          .Where(x => x.ID == faultCodeDetailID)
Run Code Online (Sandbox Code Playgroud)