0

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.

2
  • I would consider using a HashSet<string> for your Headers, that way you will have a much better lookup time. If you only have a couple headers, it might not be worth it though... Commented Apr 5, 2010 at 18:14
  • I just have a few. Thanks for the help. Commented Apr 5, 2010 at 18:32

5 Answers 5

5
checkString.Split('|').Contains(currentHeader) && Headers.Contains(currentHeader)

Using LINQ. Did I misunderstand something?

Sign up to request clarification or add additional context in comments.

Comments

1
if (!string.IsNullOrEmpty(currentHeader) && Headers.Contains(currentHeader) && checkString.Split('|').Contains(currentHeader))

Comments

1

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

2 Comments

And if _headers or _findme is null?
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.
1

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) {
    ....
}

2 Comments

+1 for culturally-sensative string comparisons! "Caf\u00E9" and "Cafe\u0301" look identical, they should compare as equal!
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!
0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.