Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for items inside a Entity Framework linq result

I am trying to check to see if any results were returned from an entity framework query before acting upon it, I'm trying to use the code :-

var shoppingCartSessions = from c in context.ShoppingCartSessions where c.UserId == gUserID select c;
if (shoppingCartSessions.First() != null)
{
}

However I get the error

Sequence contains no elements

I have checked around stack and found that I can replace .First with .FirstOrDefault however I wanted to check if this is the correct way to be checking for existence of elements. Is there a better way rather than trying to fetch the item and then checking it?

like image 234
John Mitchell Avatar asked Dec 04 '22 15:12

John Mitchell


1 Answers

Use Any():

var shoppingCartSessions = from c in context.ShoppingCartSessions 
                           where c.UserId == gUserID 
                           select c;
if (shoppingCartSessions.Any())
{
     //not empty
}
like image 61
Mahmoud Gamal Avatar answered Dec 10 '22 11:12

Mahmoud Gamal