问题VB.NET LINQ Group加入

时间:2010-12-02 17:14:07

标签: vb.net linq grouping

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

这是事情

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

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

数量服务名称
  3 Srv2 Bob
  4 Srv2 Paul
  2 Srv1 Paul
  1 Srv2尼克

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

Srv1 Paul 2
Srv1 Bob 0
Srv1尼克0
Srv2 Paul 4
Srv2 Bob 3
Srv2 Nick 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 个答案:

答案 0 :(得分:0)

我在这里得到的是我的结果,肯定有更好的方法,但无论如何,它有效

    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()