downwitch
downwitch

Reputation: 1372

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. If the user inputs a value in the wrong case, .Contains = true, which is correct, but I need to also correct the case; if e.g. 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;
    }

Upvotes: 1

Views: 143

Answers (1)

SirPentor
SirPentor

Reputation: 2044

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;
}

Upvotes: 3

Related Questions