2012-08-28 8 views
8

Provato seguendo la documentazione e non riesco a farlo funzionare. Avere un KeyedCollection con la stringa di chiavi.KeyedCollection String Case Insensitive

Come rendere insensibile la distinzione tra maiuscole e minuscole in KeyedCollection?

Su un dizionario è possibile passare StringComparer.OrdinalIgnoreCase nel 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 

risposta

7

Se si desidera che il tipo di WordDefKeyed per essere di default case-insensitive, allora il vostro difetto, costruttore senza parametri dovrebbe passare un'istanza IEqualityComparer<string> ad esso, in questo modo:

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

Il StringComparer class ha qualche difetto IEqualityComparer<T> implementazioni comunemente utilizzate a seconda del tipo di dati che si stanno archiviando:

Se avete bisogno di un StringComparer per una cultura altra di quella che è la cultura corrente, quindi è possibile chiamare il statica Create method per creare un StringComparer per una specifica CultureInfo.