LINQ – Sequence contains no elements

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.

Best Answer

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().