1

我正在尝试在 VB.net 中编写一个 linq 查询,该查询按字符串对自定义对象列表进行分组并对金额求和。我一直在使用 101 个 Linq 示例,但在尝试处理集合时遇到了 Type Expected 错误。

这是我的 Linq 查询:

Dim summedAndGrouped = From s As GLLine In _ListOfGLLines
                       Group s By s.SEDOL Into grouped = Group
                       Select SEDOL, TotalIncome = grouped.Sum(Function(s) s.Income)

改编自此处的 Linq 101 示例:http: //msdn.microsoft.com/en-us/vstudio/bb737904#sumgroup

我非常感谢任何建议。下面是我用来尝试解决这个问题的测试项目:

Imports System.Text
Imports Microsoft.VisualStudio.TestTools.UnitTesting

<TestClass()>
Public Class UnitTest1

    Private _ListOfGLLines As New List(Of GLLine)

    <TestInitialize()>
        Public Sub Setup()
        SetupGLLinesCollection()
    End Sub

    <TestMethod()>
    Public Sub TestMethod1()
        Dim summedAndGrouped = From s As GLLine In _ListOfGLLines
                               Group s By s.SEDOL Into grouped = Group
                               Select SEDOL, TotalIncome = grouped.Sum(Function(s)    s.Income)

        Assert.AreEqual(summedAndGrouped.Count, 3)
    End Sub

    Public Sub SetupGLLinesCollection()
        _ListOfGLLines.Add(New GLLine("Bob1", 20, 10, 4, 6))
        _ListOfGLLines.Add(New GLLine("Bob1", 20, 10, 4, 6))
        _ListOfGLLines.Add(New GLLine("Bob2", 20, 10, 4, 6))
        _ListOfGLLines.Add(New GLLine("Bob2", 20, 10, 4, 6))
        _ListOfGLLines.Add(New GLLine("Bob3", 20, 10, 4, 6))
        _ListOfGLLines.Add(New GLLine("Bob3", 20, 10, 4, 6))
    End Sub

End Class

Public Class GLLine
    Public Property SEDOL As String
    Public Property Income As Decimal
    Public Property PID As Decimal
    Public Property Interest As Decimal
    Public Property Dividend As Decimal

    Public Sub New(SEDOL, Income, PID, Interest, Dividend)
        _SEDOL = SEDOL
        _Income = Income
        _PID = PID
        _Interest = Interest
        _Dividend = Dividend
    End Sub
End Class

编辑:看来这个查询的评估很好,我的困惑是因为当我将鼠标悬停在 summedAndGrouped 变量上时,它给了我预期类型的​​错误,我认为这是由于编译器需要在它可以评估之前推断迭代器的类型查询。我仍然希望确认为什么会发生这种情况以及如何避免它。

4

0 回答 0