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