2012-01-12 39 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()