Tidbit: LINQ Error “Sequence contains no elements”

This generally happens when you attempt to use the First or Single method on the results of a query, such as:

    IQueryable query = /* some query */;
    var item = query.First();

If there are no results in the query, calls to the First method will generate this error. This is because the First method assumes that there will be at least one item in the result set.

If an empty result set is an expected scenario, use the FirstOrDefault method. This will return either the first item or the default value for the item type (which will vary depending on the item type) if the result set is empty.



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s