LINQ从查询结果中填充Object的嵌套列表

时间:2017-08-17 14:57:42

标签: vb.net linq

我正在加入两个表RaceOdds(加入RaceID),并希望为每个Race创建一个具有嵌套赔率的对象。通过LINQ,我可以将查询结果分组到对象中,但不能为每个Odds list填充嵌套 Race。有什么想法吗?

理想情况下,我应该

obj[0] with RaceID = 1, Odds{1,2,3}
obj[1] with RaceID = 2, Odds{4,5,6,7}

Public Class Race
   Private RaceID As Integer
   Private Name As String
   'other properties here 
   Private Odds As New List(Of Odds)
End Class

Public Class Odds
    Private OddsID As Integer
    Private Odds As System.Nullable(Of Decimal)   
    Private RaceID As Integer  
    'other properties here 
End Class

我的功能

Dim objRace As New List(Of Race)
Using context As IDataContext = DataContext.Instance()
    Dim repository = context.GetRepository(Of Race)()
    objRace = repository.Find("SELECT Odds.OddsID, Odds.Odds, Odds.Name, Odds.Type, Odds.DateUTC, Odds.WebsiteName, Odds.RaceID AS RaceID, Race.RaceID AS RaceID,
                          Race.Name AS RaceName, Race.RaceDate, Race.Location, Race.URL, Race.PortalID AS PortalID, Race.RaceTime
    FROM Odds RIGHT OUTER JOIN
                          Race ON Odds.RaceID = Race.RaceID
    WHERE (Race.PortalID = @0)",  PortalId)
End Using

LINQ获取对象

Dim result = objRace.GroupBy(Function(records) records.RaceID).[Select](Function(r) New Race() With {
    .RaceID = r.Key
    .Odds = ' <------ **somehow populate this nested list**
}).ToList()

我的查询结果: enter image description here

1 个答案:

答案 0 :(得分:-1)

r应该是IGrouping的实现。其中包含您Key使用的RaceID,其本身为IEnumerable

因此,您可以通过调用Oddsr.ToList()来存储r.ToArray。你怎么想存储它们。

我刚刚注意到您已经在构造函数中为Odds创建了列表实例。您可能想要更改此设置,因此您可以直接使用With初始化来收集集合。