Linq - Select a single child collection item

.net entity-framework linq vb.net

Question

I was wondering how to use Linq to get a single item from a parent child collection of items.

Child Collection

Public Class FaultCodeModel

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

End Class

Children's Collection

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 tried the Linq query below, but when the parent ID field matches, numerous child items are being returned.

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

How can I get only one thing from the kid collection?

1
2
1/12/2012 11:43:57 AM

Accepted Answer

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

4
1/12/2012 11:57:45 AM

Popular Answer

I believe you might like this:

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

This brings up every child item whoseID equals faultCodeDetailID .

(Since I use C#, maybe the VB.NET syntax is incorrect. Correct it yourself if possible.


Version in C#

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


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow