Www
Www

Reputation: 442

How to vary the WHERE clause of a linq to entity statement?

I am using entity framework 6.1.2 with Visual Studio 2012. Right now I have code to this effect, where min, max and item.value are doubles:

If Not Double.IsNegativeInfinity(min) AndAlso Not Double.IsPositiveInfinity(max) Then
    query = From item In query
        Where item.value >= min AndAlso item.value <= max
        select item
ElseIf Not Double.IsNegativeInfinity(min) Then
    query = From item In query
        Where item.value >= min
        select item
ElseIf Not Double.IsPositiveInfinity(max) Then
    query = From item In query
        Where item.value <= max
        select item
End If

The example provided is simple, but there are several instances with complex queries that I have to effectively write three times because entity framework doesn't know what to do with infinite doubles.

What I would like to do is replace all that with:

query = From item In query
    Where in_range(item.value, min, max)
    select item

Such that in_range expands to whatever is necessary.

Is this possible and if so, how can I do this?

Edit: Some of my queries are more complicated and involve using in_range on the result of some subquery or on differently named columns.

For example, it might be used to find all widgets where the sum of the widget's components weigh less than 20.

It might used more than once but in different columns, for example to find rectangles with heights in one range and widths in another.

I probably should have been more clear but item and value are merely placeholders for things that could really be anything.

Upvotes: 0

Views: 192

Answers (2)

scurrie
scurrie

Reputation: 403

Edit I misunderstood the original question of dealing with +/- infinity. Instead of writing three queries you could test the min/max and if either returns infinity then set them equal to Double.MaxValue or Double.MinValue and then execute the query.

Upvotes: 1

Dai
Dai

Reputation: 155708

I prefer using C# synax, but you can express Linq queries using the extension methods and manipulate them that way:

void InRange<T>(IQuerable<T> query, Double value, Double min, Double max) {
    if( Double.IsNegativeInfinity(value) ) return query.Where( i => i.value >= min);
    if( Double.IsPositiveInfinity(value) ) return query.Where( i => i.value <= max );
    return query.Where( i => i.value >= min && i.value <= max );
}

Then used like so:

query = InRange( query, item.value, min, max ).Select( i => i.whatever );

Converting this to VB should be straightforward.

Upvotes: 1

Related Questions