What .NET StringComparer is equivalent SQL's Latin1_General_CI_AS

前端 未结 4 755
借酒劲吻你
借酒劲吻你 2021-02-07 18:50

I am implementing a caching layer between my database and my C# code. The idea is to cache the results of certain DB queries based on the parameters to the query. The database i

4条回答
  •  一生所求
    2021-02-07 19:44

    The following is much simpler:

    System.Globalization.CultureInfo.GetCultureInfo(1033)
                  .CompareInfo.GetStringComparer(CompareOptions.IgnoreCase | CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth)
    

    It comes from https://docs.microsoft.com/en-us/dotnet/api/system.globalization.globalizationextensions?view=netframework-4.8

    It computes the hashcode correctly given the options given. You'll still have to trim trailing spaces manually, as they as discarded by ANSI sql but not in .net

    Here is a wrapper that trims spaces.

    using System.Collections.Generic;
    using System.Globalization;
    
    namespace Wish.Core
    {
        public class SqlStringComparer : IEqualityComparer
        {
            public static IEqualityComparer Instance { get; }
    
            private static IEqualityComparer _internalComparer =
                CultureInfo.GetCultureInfo(1033)
                           .CompareInfo
                           .GetStringComparer(CompareOptions.IgnoreCase | CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth);
    
    
    
            private SqlStringComparer()
            {
            }
    
            public bool Equals(string x, string y)
            {
                //ANSI sql doesn't consider trailing spaces but .Net does
                return _internalComparer.Equals(x?.TrimEnd(), y?.TrimEnd());
            }
    
            public int GetHashCode(string obj)
            {
                return _internalComparer.GetHashCode(obj?.TrimEnd());
            }
    
            static SqlStringComparer()
            {
                Instance = new SqlStringComparer();
            }
        }
    }
    
    

提交回复
热议问题