繁体   English   中英

如何从哈希集中获取正确大小写的值 <string> ?

[英]How do I get the correct-cased value from a hashset<string>?

我有一个使用StringComparer.CurrentCultureIgnoreCase实例化的HashSet<string> ,并且正在广泛使用.Contains(字符串输入)来检查用户输入。 如果用户在错误的情况下输入了一个值,.contains = true,这是正确的,但我还需要更正情况; 如果例如用户要求输入myvalueMyValue位于哈希集中,那么最有效的方法还可以返回MyValue以便对用户的输入进行大小写校正?

这是我的意思的粗略代码示例:

    static HashSet<string> testHS = new HashSet<string>(StringComparer.CurrentCulture);
    static bool InputExists(string input, out string correctedCaseString)
    {
        correctedCaseString = input;
        if (testHS.Contains(input))
        {
            // correctedCaseString = some query result of the cased testHS value?
            return true;
        }
        return false;
    }

您可以使用Dictionary而不是HashSet。 从字符串映射到自身,并使用不区分大小写的相等比较器(http://msdn.microsoft.com/zh-cn/library/ms132072.aspx)。 然后,您的代码将变为:

static Dictionary<string, string> testD = new Dictionary<string, string>(StringComparer.CurrentCulture);
static bool InputExists(string input, out string correctedCaseString)
{
    correctedCaseString = input;
    if (testD.ContainsKey(input))
    {
        correctedCaseString = testD[input];
        return true;
    }
    return false;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM