2012-08-28 9 views
8

Nach der Dokumentation versucht und ich kann es nicht funktionieren. Haben Sie eine KeyedCollection mit der Schlüsselzeichenfolge.KeyedCollection String Case Insensitive

Wie wird der Schlüssel in einer KeyedCollection unabhängig vom Groß- und Kleinbuchstaben gemacht?

Auf einem Wörterbuch kann nur StringComparer.OrdinalIgnoreCase im Ctor übergeben.

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 

Antwort

7

Wenn Sie Ihre Art von Standard WordDefKeyed werden Groß- und Kleinschreibung wollen, dann sollten standardmäßig parameterlos Konstruktor eine IEqualityComparer<string> Instanz, um es passieren, etwa so:

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

Die StringComparer class hat einige Standard IEqualityComparer<T> Implementierungen, die häufig verwendet in Abhängigkeit von der Art von Daten Sie speichern:

Wenn Sie eine StringComparer für eine Kultur andere als die benötigen, die die aktuelle Kultur ist, dann können Sie die statische Create method rufen Sie einen StringComparer für einen bestimmten CultureInfo zu erstellen.