2012-08-28 10 views
8

Intenté seguir la documentación y no puedo hacerlo funcionar. Tenga una KeyedCollection con la cadena clave.Cadena KeyedCollection Insensible a las mayúsculas y minúsculas

¿Cómo hacer que la clave de cadena no sea sensible a mayúsculas y minúsculas en una KeyedCollection?

En un diccionario, puede pasar StringComparer.OrdinalIgnoreCase en el 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 

Respuesta

7

Si desea que su tipo WordDefKeyed a ser sensible a las mayúsculas por defecto, entonces su defecto, constructor sin parámetros deben pasar una instancia IEqualityComparer<string> a ella, así:

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

El StringComparer class tiene algún incumplimiento IEqualityComparer<T> implementaciones que se usan comúnmente según el tipo de datos que está almacenando:

Si necesita un StringComparer para una cultura otra que la que es la cultura actual, a continuación, puede llamar a la estática Create method para crear un StringComparer para una específica CultureInfo.

Cuestiones relacionadas