Accepted answer

when you apply where/select to temp, you're not just getting a single result (there could be more than one result matching where item.glassesid==glassid, the compiler cannot be sure) so it does not return a single object instance of glasses but an ienumerable<glasses>. simplified, think that you get a list<glasses> back and you need to extract the actual object from the list before using its properties.

if you definitely know there's at most only one result returned, you can use singleordefault() which returns the glasses instance in the ienumerable or null if it's empty, or single() which returns the glasses instance in the ienumerable and throws an error if there isn't one. both throw an exception if there is more than one result.

using first() or firstordefault() would mean that if you accidentally get more than one result, you'll in this case get the first one, a random one. perhaps not a good thing for an "itemtodelete", you'd probably want to know if your assumption is wrong.


as the first() will give only a single item. so the compiler is giving intellisense for it. as the 1st version is ienumerable<glasses> so it has collection of objects. you need to iterate it.

 var itemtodelete = (from item in temp
                       where item.glassesid==glassid
                       select item);     

foreach(var i in itemtodelete )
   i.someproperty // do some thing with i ;


because your first version is a collection of glasses, not a glasses object itself. first() or firstordefault() return a single instance of glasses, thus the properties are available.


linq queries always produce a seqence of items, of type ienumerable<glasses> in your case. even if there is only one element in the sequence, it is still a sequence. the sequence itself can only be enumerated, it does not have any other properties. to get at the elements' properties you first have to extract an element. that's exactly what first() does. it returns the first element of the sequence.

if your query always should produce exactly one item and any other result is an error you should use single() instead of first(). if zero or one elements are acceptable you can use singleordefault() and check the result for null.


btw, you can hover over var in visual studio to see the type of an expression.

in this case, itemtodelete is an ienumerable<glasses> of glasses in temp with a glassesid of glassid. assuming your glassesid is actually unique in temp, it will only have one item which you can extract with .single() or .singleordefault().

edit: as others have pointed out, .single(), not .first() is the right method to use if you want to check for exactly one item.

Related Query

More Query from same tag