tags:

views:

62

answers:

2

Is this the best way to select the Fruit object I need from the ID?

So I'm taking the ID and returning its name, id being unique, so there will only ever be one result.

If I don't use .Single() I get IQueryable but I just want the single object

var fruitName = (from p in fruitDB.Fruits
                               where p.FruitID == id
                               select p.FruitName).Single();
+3  A: 

.Single() is fine - however if it doesn't have any results it will throw an exception. If you want it to return null instead do SingleOrDefault(). This will give you the only object that was returned, or if none were found, null.

If the result set will return more than 1 item (not likely with an ID), and you only want the first item, use First() or FirstOrDefault().

Michael Shimmins
+3  A: 

Try this instead

fruitDb.Fruits.SingleOrDefault(f => f.FruitId == id);
Daniel A. White