2012-01-12 15 views
2

我有父母的孩子集合對象,並想知道如何從使用LINQLINQ的 - 從子集

父集合

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 

如何從子集合中獲取單個項目?

回答

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

+0

認爲這是缺少來自Any的右括號。它去哪裏? – 2012-01-12 11:52:35

+0

謝謝蒂姆,明白了 – 2012-01-12 12:00:14

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) 
+0

不太合適。你可以發佈的C#,我會轉換? – 2012-01-12 11:56:53

+0

@PhilMurray:增加了C#版本和固定的VB.NET版本。 – 2012-01-12 11:59:47

+1

這也有用,謝謝。這裏是正確的Vb Dim var = FaultCodes.SelectMany(Function(x)x.FaultCodeDetails).Where(Function(x2)x2.ID.Equals(faultCodeDetailID)) – 2012-01-12 12:02:29

0

試試這個

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