Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

InvalidOperationException when first is not found

I'm trying to find item by item name.

Item item = Shop.Items.Values.First(i => i.Name.Contains(partOfName))

i expected to do next

if (item == null) // if not found
{
    // not found code
}

... but when item is not found i got InvalidOperationException.

The first thing that comes to mind is

try
{
    Item item = Shop.Items.Values.First(i => i.Name.Contains(partOfName))
}
catch(InvalidOperationException ex)
{
    // not found code
}

What is the best way to handle it? Maybe without try/catch?

EDIT. Solution:

Item item = Shop.Items.Values.FirstOrDefault(i => i.Name.Contains(partOfName))

if (item == null) // if not found
{
    // not found code
}
like image 525
Ronin Avatar asked Jun 08 '26 01:06

Ronin


1 Answers

First will throw. FirstOrDefault will return the default<T>. For reference types, that is null.

like image 65
Daniel A. White Avatar answered Jun 10 '26 09:06

Daniel A. White



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!