use*_*766 8 c# asp.net-mvc equality exception invalidoperationexception
我认为我的代码应该使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
}
Run Code Online (Sandbox Code Playgroud)
Ben*_*ich 14
正如您在此处所看到的,该First
方法抛出一个InvalidOperationException
调用它的序列为空的时间.由于拆分结果的元素不等于Hello5
,因此结果为空列表.First
在该列表上使用将抛出异常.
考虑使用FirstOrDefault
(在此处记录),而不是在序列为空时抛出异常,而是返回可枚举类型的默认值.在这种情况下,调用的结果将是null
,您应该在其余代码中检查它.
使用Any
Linq方法(此处记录)可能会更清晰,返回一个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
}
Run Code Online (Sandbox Code Playgroud)
现在使用三元运算符的强制性一个班轮:
string str = "Hello1,Hello,Hello2";
string another = "Hello5";
ViewBag.test = str.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
.Any(p => p == another) ? "Match" : "No Match";
Run Code Online (Sandbox Code Playgroud)
请注意,我==
在这里也用来比较字符串,这在C#中被认为是更惯用的.
归档时间: |
|
查看次数: |
61275 次 |
最近记录: |