Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can linq expression be case insensitive

i am leveraging this project to use jqgrid to filter and sort collections. The one missing feature is that this example is not doing case insensitive search which i need.

So if a user types in "Test" i want it to match with "TEST", "TeST", etc . .

i have code that looks like this:

            case WhereOperation.Equal:
                condition = Expression.Equal(memberAccessToString, filter);
                lambda = Expression.Lambda(condition, parameter);
                break;
            case WhereOperation.NotEqual:
                condition = Expression.NotEqual(memberAccessToString, filter);
                lambda = Expression.Lambda(condition, parameter);
                break;
            case WhereOperation.Contains:
                condition = Expression.Call(memberAccessToString,
                    typeof(string).GetMethod("Contains"),
                    Expression.Constant(value));
                lambda = Expression.Lambda(condition, parameter);
                break;

is there anyway to have these checks below being case insensitive so "Test" would equal "TEST"

Expression.NotEqual    
Expression.Equal
Expression.Call(memberAccessToString,
                    typeof(string).GetMethod("Contains"),
like image 554
leora Avatar asked Mar 14 '11 22:03

leora


People also ask

Is LINQ case sensitive?

LINQ has no concept of case sensitivity, it only cares about boolean evaluation. So if you want to ignore case, you should do something like: query = query.

What is expression in LINQ?

LINQ introduced the new type called Expression that represents strongly typed lambda expression. It means lambda expression can also be assigned to Expression<TDelegate> type. The . NET compiler converts the lambda expression which is assigned to Expression<TDelegate> into an Expression tree instead of executable code.

Is contains case sensitive in C#?

Contains() method in C# is case sensitive. And there is not StringComparison parameter available similar to Equals() method, which helps to compare case insensitive.


1 Answers

You could convert both values to lowercase before doing the comparison. Here's an example for Contains:

case WhereOperation.Contains:
    var toLower = Expression.Call(memberAccessToString,
                                  typeof(string).GetMethod("ToLower", System.Type.EmptyTypes));
    condition = Expression.Call(toLower,
                                typeof(string).GetMethod("Contains"),
                                Expression.Constant(value.ToString().ToLower()));
    lambda = Expression.Lambda(condition, parameter);
    break;

Note, however, that this won't pass the Turkey test.

like image 104
Heinzi Avatar answered Oct 06 '22 01:10

Heinzi