生成Lambda表达式

时间:2013-12-12 02:11:44

标签: vb.net lambda expression

根据,我有以下代码:

Public Class Fruit
    Public Property Name As String

    Public Function GetName() As String
        Return Name
    End Function
End Class
Dim list As New List(Of Fruit)

For index = 1 To 10
    Dim fruitObj As New Fruit
    fruitObj.Name = "Testing" + index.ToString()
    list.Add(fruitObj)
Next

Dim iEnumerableString As IEnumerable(Of String) = list.Select(Function(m) m.Name)

在上面的代码示例中,如果我想生成Function(m) m.Name,我应该怎么做?

所以,我可以这样称呼它:

Dim iEnumerableString As IEnumerable(Of String) =
list.Select(GenerateLambda("name"))

由于

1 个答案:

答案 0 :(得分:2)

您可以使用参数调用创建表达式树。

GeneratePropertyExpression方法:

Private Shared Function GeneratePropertyExpression(Of TSource, TResult)(propertyName As String) As Func(Of TSource, TResult)
    Dim parameter = Expression.Parameter(GetType(TSource), "x")
    Dim propertyExpression = Expression.[Property](parameter, propertyName)
    Return Expression.Lambda(Of Func(Of TSource, TResult))(propertyExpression, parameter).Compile()
End Function

用法:

Dim iEnumerableString As IEnumerable(Of String) = list.Select(GeneratePropertyExpression(Of Fruit, String)("Name"))

我没有测试过,所以如果它不起作用,请告诉我。