I have a HashSet<string>
that is instantiated using StringComparer.CurrentCultureIgnoreCase
and am making extensive use of .Contains(string input) to check user input. If the user inputs a value in the wrong case, .Contains = true, which is correct, but I need to also correct the case; 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?
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. Map from a string to itself and use a case-insensitive equality comparer (http://msdn.microsoft.com/en-us/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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.