Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/273.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用字符串和字符串数组完成if语句_C#_Asp.net_.net 3.5 - Fatal编程技术网

C# 使用字符串和字符串数组完成if语句

C# 使用字符串和字符串数组完成if语句,c#,asp.net,.net-3.5,C#,Asp.net,.net 3.5,我有一个有3个变量的页面。它们看起来像这样: String[] Headers = new String[] { "Max Width", "Max Length", "Max Height" }; String currentHeader = (String)HttpContext.Current.Request.QueryString["ItemHas"] ?? ""; String checkString = (String)HttpContext.Current.Request.Quer

我有一个有3个变量的页面。它们看起来像这样:

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"] ?? "";
检查字符串是由“|”分隔的标题列表

检查my
currentHeader
是否在my Headers数组和我的checkString字符串中的最简单方法是什么?我可以做到,但不少于20行代码。这似乎不是一个理想的解决方案

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

使用LINQ。我误解了什么吗?

写一个快速实用方法:

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;
}
试试这个:

if (Headers.Contains(currentHeader) && checkString.Split('|').Contains(currentHeader)) {
    ....
}
如果需要区分大小写:

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

也许我误解了这个问题,但这应该行得通:

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

如果_headers或_findme为null?很抱歉,我没有看到关于管道分隔字符串的行,但是您当然可以修改实用程序方法来处理它。正如Petoj所建议的那样,.Contains()方法非常简洁。+1用于文化敏感字符串比较!“Caf\u00E9”和“Caf\u0301”看起来相同,它们应该进行同等比较!但是我刚刚读了代码,你有一个严重的错误。如果
currentHeader
包含的值是
checkString
中其他分隔值之一的子字符串,则您的检查将错误地返回true。请不要让我把选票拿走!我会考虑使用HasSead为您的标题,这样您将有一个更好的查找时间。如果你只有几个标题,可能不值得…我只有几个。谢谢你的帮助。
var checks = checkString.Split('|');
if ( currentHeader.Contains(checkString) && Headers.Contains(checkString) )
{
   ....
}