首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >KeyedCollection字符串不区分大小写

KeyedCollection字符串不区分大小写
EN

Stack Overflow用户
提问于 2012-08-28 09:28:09
回答 1查看 967关注 0票数 9

我试着按照文档操作,但我不能让它工作。有一个包含密钥字符串的KeyedCollection。

如何在KeyedCollection中使字符串键不区分大小写?

可以只在ctor中传递StringComparer.OrdinalIgnoreCase。

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-08-28 11:27:38

如果您希望默认情况下类型WordDefKeyed不区分大小写,那么默认的无参数构造函数应该向其传递一个IEqualityComparer实例,如下所示:

代码语言:javascript
复制
public WordDefKeyed() : base(StringComparer.OrdinalIgnoreCase) { }

StringComparer class具有一些常用的默认IEqualityComparer<T>实现,具体取决于您要存储的数据类型:

  • StringComparer.OrdinalStringComparer.CultureInvariantIgnoreCase -当您使用机器可读字符串时使用,而不是输入或显示到cultures.
  • StringComparer.CurrentCultureStringComparer.OrdinalIgnoreCase中的字符串-当您使用不会显示给UI但对区域性敏感且在cultures.
  • StringComparer.CurrentCultureStringComparer.CurrentCultureIgnoreCase中可能相同的字符串时使用-用于特定于当前区域性的字符串,例如在收集用户输入时。

如果需要当前区域性以外的区域性的StringComparer,则可以调用静态Create method为特定CultureInfo创建StringComparer

票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12151642

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档