String.Equals() not working as intended

前端 未结 6 706
再見小時候
再見小時候 2020-11-28 10:49

I am using LINQ to search through one of my Entity Framework tables and find a \"group\" based on the name. The name is a string and appears to be Unicode (says it is in the

相关标签:
6条回答
  • 2020-11-28 11:31

    Try name.Equals(gr.Name, StringComparison.OrdinalIgnoreCase)

    If it works then the problem could be with gr.Name.

    --- Edit ---

    I'm guessing that gr.Name is not of type System.string. (since String.Equals gives you an error ==> from the previous post)

    give this a shot

    (gr.Name as string).Equals(name, StringComparison.OrdinalIgnoreCase)
    

    or

    String.Equals((gr.Name as string), name, StringComparison.OrdinalIgnoreCase)
    
    0 讨论(0)
  • 2020-11-28 11:36

    Use the String.Compare() as it can be translated to Sql.

    Here are some examples of string matching in Linq, with the Sql translation as well.

    0 讨论(0)
  • 2020-11-28 11:39

    When using LINQ to Entities, it will automatically convert it to LINQ to SQL. And if the database field you are doing a .Equals on does not have a collate of NOCASE (SQLite in my example) then it will always be case-sensitive. In otherwords, the database defines how to do the string comparison rather than code.

    0 讨论(0)
  • 2020-11-28 11:44

    Made some research. You can't do. The collation (the type of comparison) is defined at the column level of the table. You can't modify it through EF. If it's defined as case insensitive, then all the searches will be case-insensitive. If it's defined as case sensitive, then your only hope is ToUpper() the strings.

    http://connect.microsoft.com/VisualStudio/feedback/details/435783/entity-framework-conceptual-model-doesnt-support-string-equals-via-linq

    http://social.msdn.microsoft.com/Forums/en/adodotnetentityframework/thread/3810aa67-f6fe-4624-a14b-eaaa0e05ddcd

    EF4 Linq Oracle11g making queries none case-sensitive

    LINQ to Entities case sensitive comparison

    0 讨论(0)
  • 2020-11-28 11:46

    The string comparison with StringComparison.OrdinalIgnoreCase works in memory or with IEnumerable<T>. You are trying to use it with IQueryable<T>, but the provider of your queryable does not understand it.

    This works for me:

    db.Users.FirstOrDefault(
         s => s.Username.Equals(username, StringComparison.OrdinalIgnoreCase)
    );
    
    0 讨论(0)
  • 2020-11-28 11:49

    I like TravyGuy's answer from a technical perspective. For a more direct, practical answer, try using:

    string.Compare(string A, string B, StringComparison.OrdinalIgnoreCase) == 0
    
    0 讨论(0)
提交回复
热议问题