请参阅以下代码:
Public Shared Sub LinqTest()
Dim t1 As New TestPerson
t1.id = 1
t1.name = "Ian"
Dim t2 As New TestPerson
t2.id = 2
t2.name = "Lauren"
Dim list As List(Of TestPerson) = New List(Of TestPerson)
list.Add(t1)
list.Add(t2)
Dim list2 As List(Of TestPerson) = New List(Of TestPerson)
list2.Add(t1)
Dim linqresult = From p1 In list Join p2 In list2 On New With {Key p1.id, Key p1.name} Equals New With {Key p2.id, Key p2.name} Select p1.id, p1.name
End Sub
我意识到我可以这样做:
Dim list3 As New List(Of TestPerson)
For Each var In test
Dim tyPerson As New TestPerson
tyPerson.id = var.id
tyPerson.name = var.name
list3.Add(tyPerson)
Next
是否可以将.ToList与通用列表一起使用?
更新 继Ed Ednketts的评论之后;我试过这个:
Dim linqresult As List(Of TestPerson) = test.ToList
我得到的编译错误是:
Value of type 'System.Collections.Generic.List(Of <anonymous type>)' cannot be converted to 'System.Collections.Generic.List(Of com.Genie.PresentationLayer.Console.TestPerson)
我也试过这个:
Dim linqresult = test.ToList
For Each var As TestPerson In linqresult
Next
我得到的错误是:
Value of type '<anonymous type> (line 36)' cannot be converted to 'com.Genie.PresentationLayer.Console.TestPerson
答案 0 :(得分:0)
ToList
不是你的问题。您正在生成匿名类型,并尝试将其存储在已知类型的列表中。
将Linq查询更改为投影到已知类型
Dim linqresult = From p1 In list _
Join p2 In list2 _
On New With {Key p1.id, Key p1.name} _
Equals New With {Key p2.id, Key p2.name} _
Select New TestPerson With {Id = p1.id, Name = p1.name}
或
Dim linqresult = From p1 In list _
Join p2 In list2 _
On New With {Key p1.id, Key p1.name} _
Equals New With {Key p2.id, Key p2.name} _
Select p1
如果您想要列表中的实际项而不是新项。