简体   繁体   中英

How do I convert this C# lambda expression to VB.Net?

I'm attempting to convert a C# lambda that I've used many times to VB.Net, but I can't seem to figure out the correct syntax to use. Here is the original C# code:

public override IQueryable<E> Select<E>(params System.Linq.Expressions.Expression<Func<E, object>>[] includeExpressions)
{
    IQueryable<E> result = null;

    if (includeExpressions.Any())
    {
        result = includeExpressions.Aggregate<Expression<Func<E, object>>, IQueryable<E>>(Context.Set<E>(), (current, expression) => current.Include(expression));
    }

    return result;
}

I've used an online code converter and also attempted to re-write the function myself, but I'm not getting anywhere. This is what the code converter outputs when I provide the previous method:

Public Overrides Function [Select](Of E As Class)(ParamArray includeExpressions As Expression(Of Func(Of E, Object))()) As IQueryable(Of E)
    Dim result As IQueryable(Of E) = Nothing

    If includeExpressions.Any() Then
        result = includeExpressions.Aggregate(Of Expression(Of Func(Of E, Object)), IQueryable(Of E))(Context.[Set](Of E)(), Function(current, expression) current.Include(expression))
    End If

    Return result
End Function

I believe the culprit is the following:

Function(current, expression) current.Include(expression)

I don't think the code converter (and me when I tried manually) are properly formatting this lambda expression.

Here is a link to a blog post that describes the method and purpose for using in case you would like more detail: http://www.viamacchina.com/2014/01/generic-repositories-including-includes.html

The function will not compile in VB.Net. I get an error that the includeExpressions.Aggregate call does not have the correct number of parameters. I believe this is due to the second argument not (the lambda) not properly compiling and returning its result.

I think it should work if you turn Strict off, the compiler probably doesn't like the return type of the lambda. Doing it like this should also work if you want to leave Strict on, I believe:

Public Function [Select](Of E As Class)(ParamArray includeExpressions As Linq.Expressions.Expression(Of Func(Of E, Object))()) As IQueryable(Of E)
        Dim result As IQueryable(Of E) = Nothing

        If includeExpressions.Any() Then
            result = includeExpressions.Aggregate(Context.[Set](Of E)(), (Function(current, expression) CType(current.Include(expression), DbSet(Of E))))
        End If

        Return result
    End Function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM