LINQ case sensitive

前端 未结 4 1987
挽巷
挽巷 2021-01-12 14:14

How to make LINQ case sensitive and NOT case sensitive depending on the situation?

I\'m using sql server 2008 and Entity Framework 4.0.

I changed the COLLATI

相关标签:
4条回答
  • 2021-01-12 14:25

    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.Where(x => (x.Name.ToLower().Contains(Name.ToLower())));
    

    Chances are you will want to pass a CultureInfo to ToLower() (or use ToLowerInvariant()), and you might want to cache the result of Name.ToLower() so as to not have to perform that operation a potentially large number of times, but this should get you started.

    0 讨论(0)
  • 2021-01-12 14:31

    Read my reply to this:

    String.Equals() not working as intended

    It isn't the reply you wanted, probably :-)

    Ah... and if you have to convert to the same case to make comparisons, ToUpper is better than ToLower. Don't ask me why. But you can read here: Case insensitive string compare in LINQ-to-SQL

    0 讨论(0)
  • 2021-01-12 14:33
    query = query.Where(x => string.Equals(x.Name, Name, StringComparison.CurrentCultureIgnoreCase));
    
    0 讨论(0)
  • 2021-01-12 14:38

    Queryable.Contains has an overload taking an IEqualityComparer<T> used for comparision. See msdn. If you supply a case insensitive comparer, this should work - I'm quite sure there is one in the framework already.

    0 讨论(0)
提交回复
热议问题