sivaL
sivaL

Reputation: 1982

Entity framework string datatype using >,>=,<,<= operator : Lambda expression

I am working on a dynamic Lambda expression query, without using an API.

If the user selects the FieldName as "AddressLine1" and Operator as >= FieldValue as "K" It should return the results as All the AddressLine1 Field values which starts with K and L,M till Z series.

Here is the code, it works for integer datatypes:

public static Expression CreateBinaryExpression(Expression argLeft, Expression argRight, operatorType opType) {
    switch ((operatorType)opType) {    
        case operatorType.Greater:
            return Expression.GreaterThan(argLeft, argRight);
        case operatorType.GreaterEqual:
            return Expression.GreaterThanOrEqual(argLeft, argRight);
        ...
    }
}

How to modify the code to work with String datatype for Greater than Equal operator. I am looking for expression for this. Anybody have ideas?

Upvotes: 3

Views: 2174

Answers (2)

sivaL
sivaL

Reputation: 1982

got the solution from here

Dynamic Linq 2 Sql using Expressions Trees raising exception "Binary Operator LessThan not defined for System.String and System.String"

switch ((operatorType)opType) {

 case operatorType.Greater: return Expression.GreaterThan(
                            Expression.Call(typeof(string),
                            "Compare", null, new[] { argLeft, argRight }),
                             Expression.Constant(0, typeof(int)));

} 

Upvotes: 1

knittl
knittl

Reputation: 265131

You can use the String.Compare() method:

return String.Compare(argLeft, argRight) >= 0;

Compare() returns <0 if strA is less than strB, 0 when they are equal, and >0 if strA is greater than strB.

Upvotes: 4

Related Questions