我认为我的代码应该使ViewBag.test
属性等于"No Match"
,而是抛出InvalidOperationException
。
为什么会这样?
string str = "Hello1,Hello,Hello2";
string another = "Hello5";
string retVal = str.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
.First(p => p.Equals(another));
if (str == another)
{
ViewBag.test = "Match";
}
else
{
ViewBag.test = "No Match"; //this does not happen when it should
}
答案 0 :(得分:12)
如您所见here,First
方法在调用它的序列为空时抛出InvalidOperationException
。由于拆分结果的元素不等于Hello5
,因此结果为空列表。在该列表上使用First
将抛出异常。
考虑使用FirstOrDefault
代替(记录here),而不是在序列为空时抛出异常,返回可枚举类型的默认值。在这种情况下,调用的结果将是null
,您应该在其余代码中检查它。
使用Any
Linq方法(记录为here)可能会更清晰,返回bool
。
string str = "Hello1,Hello,Hello2";
string another = "Hello5";
bool retVal = str.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
.Any(p => p.Equals(another));
if (retVal)
{
ViewBag.test = "Match";
}
else
{
ViewBag.test = "No Match"; //not work
}
现在使用ternary operator强制性的一个班轮:
string str = "Hello1,Hello,Hello2";
string another = "Hello5";
ViewBag.test = str.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
.Any(p => p == another) ? "Match" : "No Match";
请注意,我在这里也使用了==
来比较字符串,这在C#中被认为是更惯用的。
答案 1 :(得分:2)
试一试:
bool hasMatch = str.Split(',').Any(x => x.Equals(another));
ViewBag.test = hasMatch ? "Match" : "No Match";