Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ - Sequence contains no elements

Tags:

linq

I am using a LINQ query as below.

object.collection.where(t => t.id.Equals("2")).First();

I am getting the error "Sequence contains no elements". Why does the result throw an error when the result contains no elements? Should it not return null when no results are found? That is what happens when using SQL.

like image 523
Thanigainathan Avatar asked Jan 10 '11 13:01

Thanigainathan


2 Answers

It's working as designed. The First() method is to be called when it's known at least one row will be returned. When this isn't the case, call FirstOrDefault().

like image 142
Randy Minder Avatar answered Nov 13 '22 20:11

Randy Minder


object.collection.where(t => t.id.Equals("2")).FirstOrDefault();
like image 6
prabhuK2k Avatar answered Nov 13 '22 22:11

prabhuK2k