我有一个包含这三项的数组:
string[] departmentArray = {
"Warranty Service Representative",
"Warranty Service Administrative Manager",
"Warranty and Site Administrator"
};
我有这个字符串
var department = "Warranty Service Representative"
我有这个条件,假设测试字符串部门是否不在departmentArray
if (Array.Exists(departmentArray, element => element != department)){
}
显然字符串在数组中,所以它应该返回false,但是对于我的字符串,这返回true。我做错了什么?
答案 0 :(得分:12)
这不会更简单吗?
string[] departmentArray = {
"Warranty Service Representative",
"Warranty Service Administrative Manager",
"Warranty and Site Administrator" };
String department = "Warranty Service Representative";
if (departmentArray.Contains(department) == false)
{
}
答案 1 :(得分:8)
if (!Array.Exists(departmentArray, element => element == department))
{
}
在这种情况下,基础逻辑看起来像:
!(departmentArray[0] == department || departmentArray[1] == department || ..)
在您的代码中,您有:
departmentArray[0] != department || departmentArray[1] != department || ..
答案 2 :(得分:1)
代码:
if (Array.Exists(departmentArray, element => element != department))
{
}
如果true
departmentArray
!=
中存在任何元素,则为department
,这就是为什么在这种情况下结果是true
而不是{{1} (显然false
中的字符串与departmentArray
不同)。因此,如果您想检查department
中department
是否不在departmentArray
,请尝试以下操作:
bool IsNotInArray(String[] array, string element){
return !Array.Exists(array, e => e == element);
}