Baahubali
Baahubali

Reputation: 4830

Expression filter on IEnumerable

i am trying to apply an expression filter dynamically and can't get it working. Would any of you guys know, how can apply the given expression filter inside the for each loop and then return the object of Type t when it matches?

Public Function FindByCondition( _
           filter As Expressions.Expression(Of Func(Of T, Boolean))) As T Implements IRepository(Of T).FindByCondition
    Dim metaData As New LinqMetaData

    AutoMapper.Mapper.CreateMap(GetType(EntityType), GetEntityType)

    Dim dataSource = TryCast(metaData.GetQueryableForEntity(CInt([Enum].Parse(GetType(EntityType), GetEntityType.Name))), IQueryable(Of EntityBase))

    Dim q = (From p In dataSource _
            Select p).ToList

    Dim g = AutoMapper.Mapper.Map(Of IEnumerable(Of T))(q)

    For Each k As T In g
        k.Equals(filter)
    Next



End Function

Upvotes: 1

Views: 545

Answers (1)

SLaks
SLaks

Reputation: 888007

You need to compile the expression tree to a delegate, then call the delegate on each instance.

Dim compiled As Func(Of T, Boolean) = filter.Compile()

If compiled(k) Then

Or, more simply,

Return g.FirstOrDefault(compiled)

Or, much more simply,

Return AutoMapper.Map(Of T)(dataSource.FirstOrDefault(filter))

This will actually run the filter on the server (or whatever your IQueryable implementation does).
For all of the other cases, you should accept a Func(Of T, Boolean) rather than an expression tree, since you don't actually need the expression tree. Compile() is an expensive call.

Upvotes: 3

Related Questions