LINQ: Sequence contains no elements

by Arnold Matusz 28 10 2008

The InvalidOperationException: Sequence contains no elements exception is thrown whenever you try to retreive an element from an empty sequence. This generally happens when you call First on an empty sequence. What I think about for this situation is that I'ld need a method which would return null if the sequence is empty and the first object (maybe the only object) in the sequence otherwise.

In this case the call of FirstOrDefault is recomended. Although after a few searches I've found something similar: we could Single or SingleOrDefault instead of First. Calling these methods is almost exactly what First does except ... this will generate another exception if the sequest contains more elements: InvalidOperationException: Sequence contains more than one element. But the convenient factor is that it quietly returns the single element in a sequence, null of the sequence is empty and the above mentioned InvalidOperationException: Sequence contains more than one element.

This is all fine until you are into ADO.NET Entity Framework like me recently. Because you are used to working by using .Single() and .SingleOrDefault() you think it's the same procedure while querying an entity data model. And you won't be pleased to see the following exception: NotSupportedException: The method 'Single' is not supported by LINQ to Entities. Consider using the method 'First' instead.

A solution to the unsuported call of Single on LINQ to Entities is the following. The query can be transformed to LINQ to Objects by calling ToList or ToArray, and because LINQ to Objects supports the Single Method, we can now call Single on the returned IEnumerable<TSource> type (Ex: .ToList().Single()). Like this we can still enjoy the ADO.NET Entity Framework and also use the Single method.

Any other ideas or solutions are welcome!

DZone it Digg it Submit to StumbleUpon Submit to Technorati Submit to reddit.com Submit to del.icio.us Submit to NewsVine Submit to Furl Submit to BlinkList

Tags: , ,

.NET 3.5 SP1 | ADO.NET | LINQ

Comments

10/29/2008 3:02:38 AM #

trackback

Trackback from DotNetKicks.com

LINQ: Sequence contains no elements

DotNetKicks.com |

8/17/2009 1:38:44 AM #

Sunil

I used following easy work around. use count() if count is zero then return default value or null, else return first() record


    public int GetPKey(int year, int week, int day)
    {
      int Year = year;
      int Week = week;
      int Day = day;

      try
      {
        var pk = from l in datacontext.table
                          where l.Year== Year
               where l.Week == Week
               where l.Day == Day
               select l.Pkey;

        if (pk.Count() != 0) // if there will be element then function will send first element  , in fact this will be the only element
        {
          return pk.First();
        }
        else
        {
          return -1; // if there will be no record then function will return -1
        }

      
      }
      catch (Exception e)
      {
                                            // catch exception here
      }
    
    }

Sunil United Kingdom |