问题VB.NET LINQ集团加入

好的,我知道这里有很多帖子,但我试图解决这个问题几个小时,我的大脑完全没了 .

这就是事情

我有一个包含3个属性的对象列表(数量,服务,名称)

我希望列表中的所有名称和服务(有点交叉连接)和相应行的分组数量 . 我猜不清楚

数量服务名称
3 Srv2鲍勃
4 Srv2保罗
2 Srv1保罗
1 Srv2尼克

我想作为输出
所有服务以及所有名称和相应数量(如果没有,则为0)

Srv1保罗2
Srv1 Bob 0
Srv1尼克0
Srv2保罗4
Srv2鲍勃3
Srv2尼克1

这是我到目前为止所得到的,但我甚至没有得到预期的结果而且我确实有一种非常简单的方法来实现我想要的...我会得到一点帮助...

谢谢

Dim services = (From a In interventions Select New With {.Service = a.Service}).Distinct()
    Dim months = (From b In interventions Select New With {.Month = b.DateHeureIntervention.Month}).Distinct()

    'Dim query = (From s In services _
    '             From m In months _
    '             From i In interventions.Where(Function(x) x.Service = s.Service And x.DateHeureIntervention.Month = m.Month).DefaultIfEmpty(New Intervention()) _
    '             Select New ChartItem With {.Service = s.Service, _
    '                                        .Name = MonthName(m.Month), _
    '                                        .Quantite = i.Quantite}).ToList()

    'Return (From q In query _
    '       Group By srv = q.Service, n = q.Name Into Group _
    '       Select New ChartItem With {.Name = n, _
    '                                  .Service = srv, _
    '                                  .Quantite = Group.Sum(Function(i) i.Quantite)}).ToList()


    Dim q = (From i In interventions _
            Group Join s In services On s.Service Equals i.Service Into si = _
            Group Join m In months On m.Month Equals i.DateHeureIntervention.Month _
            From x In si.DefaultIfEmpty() _
            Group By m = i.DateHeureIntervention.Month, srv = i.Service Into Group _
            Select New ChartItem With {.Service = srv, _
                                       .Name = MonthName(m), _
                                       .Quantite = Group.Sum(Function(y) y.i.Quantite)}).ToList()

    Return q

回答(1)

2 years ago

我得到它是我的结果,肯定有更好的方法,但无论如何,它的工作原理

Dim months As List(Of Integer) = (From b In interventions Select b.DateHeureIntervention.Month).Distinct().ToList()
    Dim services As List(Of String) = (From c In interventions Select c.Service).Distinct().ToList()

    Dim q = (From s In services _
             From m In months _
             Select New ChartItem With {.Name = MonthName(m), _
                                        .Service = s, _
                                        .Quantite = (From i In AccesDonneesHelper.GetInterventionsDetails() _
                                                     Where i.Service = s And i.DateHeureIntervention.Month = m _
                                                     Select i.Quantite).Sum()}).ToList()