VB.net使用Lambda表达式迭代匿名类型集合



我试图通过匿名类型集合进行迭代,但得到System.MissingMemberExceptionHResult=0x80131512Message=重载解析失败,因为没有可访问的"ForEach"接受此数量的参数。无法确定原因。我成功地使用了For Each,但无法使用Lambda表达式。

Dim car As Object = {(New With {Key .Model = "Buick", .Color = "Blue"}),
(New With {Key .Model = "Volvo", .Color = "Green"}),
(New With {Key .Model = "Jeep", .Color = "Red"})}
For Each item In car
If item.Color = "Blue" Then Debug.Print(String.Format("{0} {1}", item.Model, item.Color))
Next
car.ForEach(Sub(x)
Debug.Print(String.Format("[0} {1}", x.model, x.color))
End Sub)

ForEach是List(Of T(的东西,而不是LINQ的东西。。

Dim cars = ({ New With {Key .Model = "Buick", .Color = "Blue"},
New With {Key .Model = "Volvo", .Color = "Green"},
New With {Key .Model = "Jeep", .Color = "Red"}
}).ToList()

这将汽车创建为一个匿名数组,然后使用ToList从中生成一个列表;ForEach则可用

注:集合使用复数

感谢您为我指明了正确的方向,下面是我想要的一个工作示例。

Imports System
Imports System.Linq
Public Module Module1

Public Sub Main()

Dim cars = ({ New With { .Model = "Buick", .Color = "Blue"},
New With { .Model = "Volvo", .Color = "Green"},
New With { .Model = "Jeep", .Color = "Red"}
})
cars.AsEnumerable.ToList().ForEach(sub(x) 
console.WriteLine(string.format("Model: {0}  Color: {1}", x.Model, x.Color ))
End Sub)
End Sub
End Module

最新更新