System.InvalidOperationException: Sequence contains no elements

by rahul 3/26/2009 8:56:00 AM

While using LINQ, let’s say you decide to do something similar to the following…

    NorthWindDataContext dc = new NorthWindDataContext();
    Product p = dc.Products.First(p1 => p1.ProductName.StartsWith("My New Product"));
    if (p == null)
        return;

    dc.Products.DeleteOnSubmit(p);
    dc.SubmitChanges();
    ShowProducts();

Everything would be fine if you do have a product whose name starts with “My New Product”, but what do you think would happen if that’s not the case? Well surprisingly... you would get an un-handled runtime exception!!!

Exception Details: System.InvalidOperationException: Sequence contains no elements
Source Error:

Line 69:         NorthWindDataContext dc = new NorthWindDataContext();
Line 70: 
Line 71:         Product p = dc.Products.First(p1 => p1.ProductName.StartsWith("My New Product"));
Line 72:         if (p == null)
Line 73:             return;

To get rid of this error, instead of using dc.Products.First, use dc.Products.FirstOrDefault and you should be good!

Happy Coding. Wave
Rahul

 


Quote of the day:
Few people can see genius in someone who has offended them. - Robertson Davies


blog comments powered by Disqus

Rahul Soni

Rahul Soni  Twitter

 LinkedIn

 Facebook

 Email me



Vivek Kumbhar

Vivek Kumbhar  Twitter

 LinkedIn

 Facebook

 Email me


Stack Exchange

profile for Vivek at Server Fault, Q&A for system administrators and IT professionals

profile for Rahul Soni at Stack Overflow, Q&A for professional and enthusiast programmers

Calendar

<<  February 2012  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
2728291234
567891011

View posts in large calendar

All Items
Sign in

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© Copyright 2012, Rahul Soni

Powered by BlogEngine.NET 1.4.5.0