为什么这段代码会抛出InvalidOperationException异常?

11
我认为我的代码应该使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
}

@SLaks 这段代码返回了 System.InvalidOperationException 而不是在页面上显示 "No Match"。 - user2398766
它不会返回 InvalidOperationException,而是抛出它。主要是因为该列表中没有任何一个字符串等于“Hello5”。你想要实现什么? - It'sNotALie.
2
如果没有匹配项,.First() 会抛出异常,请尝试使用FirstOrDefault() 并检查 null。 - Laszlo Boke
2个回答

18

正如您可以在这里看到的那样,当调用它的序列为空时,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
}

现在,使用三目运算符的强制一行代码:

string str = "Hello1,Hello,Hello2";
string another = "Hello5";
ViewBag.test = str.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
                   .Any(p => p == another) ? "Match" : "No Match";

需要注意的是,我在这里使用了 == 来比较字符串,在C#中被认为更符合惯用语。


2
我本来想点个赞,但是代码不清晰,我完全不知道他/她在尝试做什么。 - It'sNotALie.
1
我理解这个问题是,当变量str在逗号之间包含变量another时,将ViewBag.test设置为“Match”,否则设置为“No Match”。@user2398766,你是这个意思吗? - Ben Reich
我同意,但我说不出来! - It'sNotALie.

2
试试这个:

尝试一下:

bool hasMatch = str.Split(',').Any(x => x.Equals(another));

ViewBag.test = hasMatch ? "Match" : "No Match";

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接