Sequence contains no elements

So I had some very basic code that I was using to pull bugs from a List of bugs, like so:

int bugId = 42; // Hard-coded for your enjoyment
List<BugClass> bugs =  PopulateBugs();
var theBugIWant = bugs.First(b => b.BugID == bugId);

As you can guess, my BugClass has a field called BugID.

When I ran this query, I got this message:

 “Sequence contains no elements”

 Well, there goes some of my joie de vivre.

But luckily, it came back quickly – you can’t keep a good joie down. I just did a simple change from First to FirstOrDefault, and that resolved the cases where a particular bug wasn’t in the database:

 var theBugIWant = bugs.FirstOrDefault(b => b.BugID == bugId);

 theBugIWant now returns null, but that is something I can deal with more gracefully than an exception.

About these ads
  1. Leave a comment

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: