按名称列出的Linq订单和第2组项目

时间:2014-01-03 18:01:42

标签: vb.net linq sorting visual-studio-2012

我有以下输入:

 Public Function GetProgramTitles() As List(Of ProgramTitle)
    Dim x As New List(Of ProgramTitle)

    x.Add(New ProgramTitle("Outlook.exe", "email1"))
    x.Add(New ProgramTitle("Outlook.exe", "email2"))
    x.Add(New ProgramTitle("Outlook.exe", "email1"))
    x.Add(New ProgramTitle("Outlook.exe", "email2"))
    x.Add(New ProgramTitle("Outlook.exe", "email1"))
    x.Add(New ProgramTitle("Word.exe", "Doc1"))
    x.Add(New ProgramTitle("Outlook.exe", "email2"))
    x.Add(New ProgramTitle("Word.exe", "Doc2"))
    x.Add(New ProgramTitle("Outlook.exe", "email1"))

    Return x
End Function

我想接受这些数据并返回类似的内容:

Outlook.exe - 7(程序实例)
-email1 - 4
-email2 - 3
Word.exe - 2
-Doc1 - 1
-Doc2 - 1

这是我到目前为止所做的:

    Dim data = GetProgramTitles()

    Dim programs = From c In data Select New With {c.Program, c.Title,
        .Programs =
        From o In c.Program
        Group o By c.Program Into Group
        Select New With {.Title = c.Title,
                            .TitleGroup =
                            From o In Group
                            Group o By c.Title Into TitleGroup = Group
                            Select New With {.Program = Program, .Title = TitleGroup}}}

    For Each p In programs
        Console.WriteLine("Program: " & p.Program & " - " & p.Title & " - " & p.Program.Count)
    Next

我得到的回报根本没有排序,我无法弄清楚如何解决这个问题。

1 个答案:

答案 0 :(得分:2)

我不确定您为什么要在内部查询中使用Group By,而不是在主查询中。

Dim programs =
    From d In data
    Group d By dk = d.Program Into dg = Group, dc = Count()
    Order By dc Descending
    Select New With {
        .Program = dk,
        .Count = dc,
        .Titles =
            From t In dg
            Group t By tk = t.Title Into tg = Group, tc = Count()
            Select New With {
                .Title = tk,
                .Count = tc
            }
    }

我稍微更改了返回的匿名类型结构,因此您还必须更改For Each循环,

For Each p In programs
    Console.WriteLine("Program: {0} - {1}", p.Program, p.Count)
    For Each t In p.Titles
        Console.WriteLine("Title: {0} - {1}", t.Title, t.Count)
    Next
Next

打印

Program: Outlook.exe - 7
Title: email1 - 4
Title: email2 - 3
Program: Word.exe - 2
Title: Doc1 - 1
Title: Doc2 - 1