我正在尝试在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变量上时它给出了Type Expected错误,我认为是由于编译器需要先推断迭代器的类型它可以评估查询。我仍然希望确认为什么会发生这种情况以及如何避免它。