未找到第一个时出现 InvalidOperationException
InvalidOperationException when first is not found
我正在尝试按项目名称查找项目。
Item item = Shop.Items.Values.First(i => i.Name.Contains(partOfName))
我预计接下来会做
if (item == null) // if not found
{
// not found code
}
...但是当找不到项目时我得到 InvalidOperationException
.
首先想到的是
try
{
Item item = Shop.Items.Values.First(i => i.Name.Contains(partOfName))
}
catch(InvalidOperationException ex)
{
// not found code
}
最好的处理方法是什么?也许没有 try/catch?
编辑。
解决方案:
Item item = Shop.Items.Values.FirstOrDefault(i => i.Name.Contains(partOfName))
if (item == null) // if not found
{
// not found code
}
First
会抛出。 FirstOrDefault
将 return default<T>
。对于引用类型,即 null
.
我正在尝试按项目名称查找项目。
Item item = Shop.Items.Values.First(i => i.Name.Contains(partOfName))
我预计接下来会做
if (item == null) // if not found
{
// not found code
}
...但是当找不到项目时我得到 InvalidOperationException
.
首先想到的是
try
{
Item item = Shop.Items.Values.First(i => i.Name.Contains(partOfName))
}
catch(InvalidOperationException ex)
{
// not found code
}
最好的处理方法是什么?也许没有 try/catch?
编辑。 解决方案:
Item item = Shop.Items.Values.FirstOrDefault(i => i.Name.Contains(partOfName))
if (item == null) // if not found
{
// not found code
}
First
会抛出。 FirstOrDefault
将 return default<T>
。对于引用类型,即 null
.