Elegant way of converting between StringComparison and StringComparer?

前端 未结 5 1211
醉梦人生
醉梦人生 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:13

    There isn't something out of the box, but you can create a simple mapping yourself between the comparsion and the comparer:

    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 }
    }
    

    And when-ever you need the proper comparer:

    var invariantComparer = comparsionToComparer[StringComparsion.InvariantCulture];
    

    Edit:

    With C#-6 Dictionary Initializer syntax:

    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
    };
    

    Also, Jons answer refers to the issue of the threads current-culture, which i discarded and should probably be taken into account

提交回复
热议问题