RoughPlace
RoughPlace

Reputation: 1121

how to handle empty linq Queries

I'm sure there is a better way of writing the following would love a few pointers on how to best go about it

essentially i cannot guarantee that a list of item contains a specific item i'm after and in trying to return a value based upon said item.

class item
{
string Brand;
string Product;
decimal Value;
}

//List is created and filled elsewhere
List<item> _items;

void DoStuff()
{
decimal desiredValue = 0;

   try
     {
    var XXX = _items
             .Where(x=>x.Brand == "brand1")
             .Where(x=>x.Product == "product1")
             .First();

    desiredValue = XXX.Value;
     }
    catch()
     { 
     //Empty Catch Bugs me
     }
//Do something with desiredValue
   }
}

Upvotes: 2

Views: 2578

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1500425

I would use:

decimal? result = _items.Where(x => x.Brand == "brand1")
                        .Where(x => x.Product == "product1")
                        .Select(x => (decimal?) x.Value)
                        .FirstOrDefault();

Note that here the Select clause is fetching something which is a non-nullable decimal, but explicitly converting it to decimal? so that you can then tell the difference between "there was a result, but it was 0" and "there weren't any results":

if (result == null)
{
    // No results
}
else
{
    decimal realResult = result.Value;
    // whatever...
}

Alternatively, you could use:

Item result = _items.FirstOrDefault(x => x.Brand == "brand1" && 
                                         x.Product == "product1");

if (result == null)
{
    // No results
}
else
{
    decimal value = result.Value;
    // Proceed...
}

Upvotes: 5

Massimiliano Peluso
Massimiliano Peluso

Reputation: 26737

var result= _items.Where(x=>x.Brand = "brand1" && x.Product="product1").FirstOrDefault()

if (result!=null)
{
    // get the first
    var firstItem = result.value;
}

Upvotes: 2

Avner Shahar-Kashtan
Avner Shahar-Kashtan

Reputation: 14700

Instead of First(), use FirstOrDefault(), which will return null, which you can then check for.

Upvotes: 2

Related Questions