KeyedCollection String is insensitive

Tried to follow the documentation, and I can't get it to work. Have a KeyedCollection with a key string.

How to make string key case insensitive in KeyedCollection?

In the dictionary, you can simply pass StringComparer.OrdinalIgnoreCase to 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 
+8
string-comparison iequalitycomparer
source share
1 answer

If you want your WordDefKeyed type to be case insensitive by default, then your constructor without parameters without a space should pass an IEqualityComparer<string> instance to it, for example:

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

StringComparer class has several standard implementations of IEqualityComparer<T> , which are usually used depending on the type of data you store:

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

+7
source share

All Articles