Question

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
Was it helpful?

Solution

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:

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top