Search code examples
c#linqinvalidoperationexception

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
}

Solution

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