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