[英]How do I get the correct-cased value from a hashset<string>?
I have a HashSet<string>
that is instantiated using StringComparer.CurrentCultureIgnoreCase
and am making extensive use of .Contains(string input) to check user input. 我有一个使用
StringComparer.CurrentCultureIgnoreCase
实例化的HashSet<string>
,并且正在广泛使用.Contains(字符串输入)来检查用户输入。 If the user inputs a value in the wrong case, .Contains = true, which is correct, but I need to also correct the case; 如果用户在错误的情况下输入了一个值,.contains = true,这是正确的,但我还需要更正情况; if eg the user asks for
myvalue
and MyValue
is in the hashset, what is the most efficient way to also return MyValue
so the user's input is case-corrected? 如果例如用户要求输入
myvalue
且MyValue
位于哈希集中,那么最有效的方法还可以返回MyValue
以便对用户的输入进行大小写校正?
Here's a rough code sample of what I mean: 这是我的意思的粗略代码示例:
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;
}
You could use a Dictionary instead of a HashSet. 您可以使用Dictionary而不是HashSet。 Map from a string to itself and use a case-insensitive equality comparer (http://msdn.microsoft.com/en-us/library/ms132072.aspx).
从字符串映射到自身,并使用不区分大小写的相等比较器(http://msdn.microsoft.com/zh-cn/library/ms132072.aspx)。 Your code then becomes something like:
然后,您的代码将变为:
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.