Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to check for upper/lower case query strings

I have a problem where I need to extract a query string parameter from a url. The parameter could be either "Territory" or "territory" or other upper/lower case variations of that word. Although the following works for the first two cases I wonder if there is a better way?

IDictionary<string, string> queryString = HtmlPage.Document.QueryString;

if (queryString.ContainsKey("territory"))
{
    ish.SetDefaultRegion(int.Parse(queryString["territory"]));
    // do something (the same something as below)
}
else if (queryString.ContainsKey("Territory"))
{
    ish.SetDefaultRegion(int.Parse(queryString["Territory"]));
    // do something (the same something as above)
}

I would prefer to insert the query string into the dictionary ignoring case (ie. if the user accidentally typed "TERRITORY" this code would fail, so how can I just test that the word exists regardless of casing?

like image 611
rmcsharry Avatar asked May 03 '12 16:05

rmcsharry


People also ask

How can we check both lowercase and uppercase in SQL?

Case sensitive search in SQL Server can be achieved either by using COLLATE or by using BINARY_CHECKSUM(). COLLATE is the T-SQL clause used to define collation. BINARY_CHECKSUM() is a built-in system function used to compare the binary check-sum value.

How do you know if a string is upper and lowercase?

Traverse the string character by character from start to end. Check the ASCII value of each character for the following conditions: If the ASCII value lies in the range of [65, 90], then it is an uppercase letter. If the ASCII value lies in the range of [97, 122], then it is a lowercase letter.

How do I select lowercase letters in SQL?

Use the SQL LOWER() function if you want to convert a string column to lowercase. This function takes only one argument: the column whose values you want to lowercase. This function is a good choice if your database is case sensitive and you want to select only records matching a particular string.


2 Answers

Use a dictionary with a case-insensitive key comparer:

var queryParams = new Dictionary<string, string>(
    HtmlPage.Document.QueryString,
    StringComparer.InvariantCultureIgnoreCase
);

if (queryParams.ContainsKey("territory")) {
    // Covers "territory", "Territory", "teRRitory", etc.
}
like image 162
Cameron Avatar answered Sep 20 '22 18:09

Cameron


If your QueryString Object is not a dictionary object but instead is something such as a NameValueCollection...

IDictionary<string, string> queryString = QueryString.AllKeys.ToDictionary(k => k.ToLowerInvariant(), k => QueryString[k]);
like image 28
George Avatar answered Sep 20 '22 18:09

George