I have a parent child collection objects and was wondering how to get a single item from the child collection using 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
I have tried the below Linq query but it is returning multiple child items where the parent ID field is matched.
Dim var = From fcd In FaultCodes Where fcd.FaultCodeDetails.Any(Function(w) w.ID.Equals(faultCodeDetailID)) Select fcd.FaultCodeDetails
How do I get a single item from the child collection?
Dim fcdID = 4711 Dim fcdm = (From fc In FaultCodes From fcd In fc.FaultCodeDetails Where fcd.ID = fcdID Select fcd).FirstOrDefault
I think you want to have this:
FaultCodes.SelectMany(Function(w) w.FaultCodeDetails) .Where(Function(w) w.ID.Equals(faultCodeDetailID))
This returns all the child items whose
(I am a C# guy, maybe the VB.NET syntax is a bit off. Please correct it yourself)
FaultCodes.SelectMany(x => x.FaultCodeDetails) .Where(x => x.ID == faultCodeDetailID)