2012-08-28 132 views
8

試過以下的文檔,我無法使它工作。使用鍵字符串獲得KeyedCollection。KeyedCollection字符串大小寫不敏感

如何使KeyedCollection中的字符串不區分大小寫?

上一個詞典可以只傳遞StringComparer.OrdinalIgnoreCase在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 

回答

7

如果你希望你的類型WordDefKeyed是不區分大小寫默認情況下,那麼你的默認參數的構造函數應該傳遞一個IEqualityComparer<string>實例給它,像這樣:

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

StringComparer class有一些默認IEqualityComparer<T>實施通常根據您正在存儲的數據類型而使用:

如果你需要一個文化其他比一個是當前文化StringComparer,那麼你可以調用靜態Create method爲特定CultureInfo創建StringComparer