Ronin
Ronin

Reputation: 2288

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
}

Upvotes: 1

Views: 4133

Answers (1)

Daniel A. White
Daniel A. White

Reputation: 190976

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

Upvotes: 8

Related Questions