2012-08-28 134 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