views:

94

answers:

5

I have a page that has 3 variables. They look like this:

String[] Headers = new String[] { "Max Width", "Max Length", "Max Height" };
String currentHeader = (String)HttpContext.Current.Request.QueryString["ItemHas"] ?? "";
String checkString = (String)HttpContext.Current.Request.QueryString["ItemIn"] ?? "";

The checkString is a list of Headers delimited by a "|".

What is the easiest way to check if my currentHeader is in my Headers array and in my checkString String? I can do it but not in less than 20 lines of code. That seems like a less than optimal solution.

+1  A: 
if (!string.IsNullOrEmpty(currentHeader) && Headers.Contains(currentHeader) && checkString.Split('|').Contains(currentHeader))
Petoj
+5  A: 
checkString.Split('|').Contains(currentHeader) && Headers.Contains(currentHeader)

Using LINQ. Did I misunderstand something?

flq
+1  A: 

Write a quick utility method:

private bool IsInHeader(string[] _headers, string _findme)
{
    if (_headers == null || _findme == null) return false;
    foreach (string s in _headers)
    {
        if (_findme == s) return true;
    }
    return false;
}
JYelton
And if _headers or _findme is null?
n535
Sorry I didn't see the line about the pipe-delimited string, but certainly you could modify the utility method to handle it. Also as Petoj suggested, the .Contains() method is concise.
JYelton
@n535 good point, I added a line to handle such a condition.
JYelton
+1  A: 

Try this:

if (Headers.Contains(currentHeader) && checkString.Split('|').Contains(currentHeader)) {
    ....
}

And if you need it to be case-insensitive:

if (Headers.Contains(currentHeader, StringComparer.InvariantCultureIgnoreCase) 
    && checkString.Split('|').Contains(currentHeader, StringComparer.InvariantCultureIgnoreCase) {
    ....
}
Chris Pebble
+1 for culturally-sensative string comparisons! "Caf\u00E9" and "Cafe\u0301" look identical, they should compare as equal!
Jeffrey L Whitledge
But I just read the code, and you have a serious bug. If `currentHeader` contains a value that is a substring of one of the other delimited values in `checkString`, then your check will incorrectly return true. Don't make me take my vote away, please!
Jeffrey L Whitledge
Yowza, thanks for pointing that out. Fixed.
Chris Pebble
Much better. Thanks. :-)
Jeffrey L Whitledge
A: 

Perhaps I am misunderstanding the question, but this should work:

var checks = checkString.Split('|');
if ( currentHeader.Contains(checkString) && Headers.Contains(checkString) )
{
   ....
}
driis