Elegant way of converting between StringComparison and StringComparer?

前端 未结 5 1212
醉梦人生
醉梦人生 2021-01-18 02:49

Some .NET methods use StringComparison as parameter, some use StringComparer (often in form of IComparer). The difference is clear. Is there some elegant way how to get

5条回答
  •  暖寄归人
    2021-01-18 03:24

    An a complete extension method for any one who needs quick copy+paste:

    public static class StringComparisonExtensions
    {
      // from http://stackoverflow.com/a/32764112/548304
      private static readonly Dictionary> ComparsionToComparer =
        new Dictionary>
          {
            [StringComparison.CurrentCulture] = () => StringComparer.CurrentCulture,
            [StringComparison.CurrentCultureIgnoreCase] = () => StringComparer.CurrentCultureIgnoreCase,
            [StringComparison.InvariantCulture] = () => StringComparer.InvariantCulture,
            [StringComparison.InvariantCultureIgnoreCase] = () => StringComparer.InvariantCultureIgnoreCase,
            [StringComparison.Ordinal] = () => StringComparer.Ordinal,
            [StringComparison.OrdinalIgnoreCase] = () => StringComparer.OrdinalIgnoreCase
          };
    
      /// 
      ///  Retrieves a string comparer for the given StringComparison.
      /// 
      public static StringComparer ToComparer(this StringComparison comparison)
      {
        return ComparsionToComparer.GetValueOrDefault(comparison)?.Invoke();
      }
    }
    

提交回复
热议问题