Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KeyedCollection String Case Insensitive

Tried following the documentation and I cannot make it work. Have a KeyedCollection with the key string.

How to make the string key case insensitive in a KeyedCollection?

On a Dictionary can just pass StringComparer.OrdinalIgnoreCase in the ctor.

private static WordDefKeyed wordDefKeyed = new WordDefKeyed(StringComparer.OrdinalIgnoreCase);   // this fails

public class WordDefKeyed : KeyedCollection<string, WordDef>
{
        // The parameterless constructor of the base class creates a 
        // KeyedCollection with an internal dictionary. For this code 
        // example, no other constructors are exposed.
        //
        public WordDefKeyed() : base() { }

        public WordDefKeyed(IEqualityComparer<string> comparer)
            : base(comparer)
        {
            // what do I do here???????
        }

        // This is the only method that absolutely must be overridden,
        // because without it the KeyedCollection cannot extract the
        // keys from the items. The input parameter type is the 
        // second generic type argument, in this case OrderItem, and 
        // the return value type is the first generic type argument,
        // in this case int.
        //
        protected override string GetKeyForItem(WordDef item)
        {
            // In this example, the key is the part number.
            return item.Word;
        }
}

private static Dictionary<string, int> stemDef = new Dictionary<string, int(StringComparer.OrdinalIgnoreCase);   // this works this is what I want for KeyedCollection
like image 267
paparazzo Avatar asked Aug 28 '12 01:08

paparazzo


1 Answers

If you want your type WordDefKeyed to be case-insensitive by default, then your default, parameterless constructor should pass an IEqualityComparer<string> instance to it, like so:

public WordDefKeyed() : base(StringComparer.OrdinalIgnoreCase) { }

The StringComparer class has some default IEqualityComparer<T> implementations that are commonly used depending on the type of data you are storing:

  • StringComparer.Ordinal and StringComparer.OrdinalIgnoreCase - Used when you're using machine-readable strings, not strings that are entered or displayed to the user.

  • StringComparer.InvariantCulture and StringComparer.CultureInvariantIgnoreCase - Used when you're using strings that won't be shown to the UI, but are sensitive to culture and may be the same across cultures.

  • StringComparer.CurrentCulture and StringComparer.CurrentCultureIgnoreCase - Use for strings that are specific to the current culture, such as when you're gathering user input.

If you need a StringComparer for a culture other than the one that is the current culture, then you can call the static Create method to create a StringComparer for a specific CultureInfo.

like image 119
casperOne Avatar answered Nov 16 '22 03:11

casperOne