首页 > 解决方案 > VB.net 使用 Lambda 表达式迭代匿名类型集合

问题描述

我试图遍历匿名类型集合,但得到 System.MissingMemberException HResult=0x80131512 Message=Overload resolution failed 因为没有可访问的“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)

标签: vb.netlambda

解决方案


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

注意:集合使用复数


推荐阅读