Elegant way of converting between StringComparison and StringComparer?

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

    Going from StringComparison to StringComparer is simple - just create a Dictionary:

    var map = new Dictionary
    {
        { StringComparison.Ordinal, StringComparer.Ordinal },
        // etc
    };
    

    There is a StringComparer for every StringComparison value, so that way works really easily. Mind you, StringComparer.CurrentCulture depends on the current thread culture - so if you populate the dictionary and then modify the thread's culture (or do it from a different thread with a different culture) you may end up with the wrong value. You potentially want a Dictionary>:

    var map = new Dictionary>
    {
        { StringComparison.Ordinal, () => StringComparer.Ordinal },
        // etc
    };
    

    Then you can get a comparer at any time by invoking the delegate:

    var comparer = map[comparison]();
    

    Going the other way is infeasible, because not every StringComparer has a suitable StringComparison. For example, suppose I (in the UK) create a StringComparer for French (StringComparer.Create(new CultureInfo(..., true)). Which StringComparison does that represent? It's not correct for the current culture, the invariant culture, or ordinal comparisons.

提交回复
热议问题