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

时间:2012-01-12 11:43:58

标签: .net vb.net linq 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

儿童收藏

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

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

Dim var = From fcd In FaultCodes Where fcd.FaultCodeDetails.Any(Function(w) w.ID.Equals(faultCodeDetailID))
            Select fcd.FaultCodeDetails

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

3 个答案:

答案 0 :(得分:4)

Dim fcdID = 4711
Dim fcdm = (From fc In FaultCodes
           From fcd In fc.FaultCodeDetails
           Where fcd.ID = fcdID
        Select fcd).FirstOrDefault

http://msdn.microsoft.com/en-us/library/bb340482.aspx

答案 1 :(得分:3)

我想你想要这个:

FaultCodes.SelectMany(Function(w) w.FaultCodeDetails)
          .Where(Function(w) w.ID.Equals(faultCodeDetailID))

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

(我是C#的家伙,也许VB.NET语法有点不对。请自行更正)


C#版本:

FaultCodes.SelectMany(x => x.FaultCodeDetails)
          .Where(x => x.ID == faultCodeDetailID)

答案 2 :(得分:0)

试试这个

 Dim Obj = (yourcollection).Where(Function(c) c.FieldName.ToString() = "YourValue").FirstOrDefault()