linq表达式不区分大小写

时间:2011-03-14 22:44:13

标签: c# linq comparison expression

我正在利用this project to use jqgrid to filter and sort collections。缺少的一个特性是这个例子没有做我需要的不区分大小写的搜索。

因此,如果用户键入“Test”,我希望它与“TEST”,“TeST”等匹配。

我的代码如下:

            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;
无论如何,以下这些检查是不区分大小写的,所以“测试”将等于“测试”

Expression.NotEqual    
Expression.Equal
Expression.Call(memberAccessToString,
                    typeof(string).GetMethod("Contains"),

4 个答案:

答案 0 :(得分:18)

在进行比较之前,您可以将两个值都转换为小写。以下是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;

但请注意,这是won't pass the Turkey test

答案 1 :(得分:9)

不幸的是,BCL没有Contains重载,允许您指定大小写不变性。您必须获取IndexOf的正确重载作为解决方法(检查IndexOf的结果是否大于零):

var methodInfo 
    = typeof(string)
        .GetMethod("IndexOf", 
            new[] { typeof(string), typeof(StringComparison) });

MethodInfo接受stringStringComparison,如果您愿意,可以指定StringComparison.OrdinalIgnoreCase

答案 2 :(得分:2)

你得到以下方式:

First Extend string class:

internal static class StringExtensions

    {
        public static bool ContainsExt(this String str, string val)
        {
            return str.IndexOf(val, StringComparison.InvariantCultureIgnoreCase) > -1 ? true : false;
        }
    }

现在将Expression调用编写为

Expression.Call(null,
                    typeof(StringExtensions).GetMethod("ContainsExt", new Type[] { typeof(String), typeof(String) }),
                    new[] { memberAccessToString, Expression.Constant(value));

答案 3 :(得分:2)

case WhereOperation.Contains:
     var callEx = Expression.Call(memberAccess, typeof(string).GetMethod("IndexOf", new[] { typeof(string), typeof(StringComparison) }), Expression.Constant(value), Expression.Constant(StringComparison.OrdinalIgnoreCase));
     condition = Expression.NotEqual(callEx, Expression.Constant(-1));
     lambda = Expression.Lambda(condition, parameter);
     break;