Sequence contains no elements exception in linq without even using Single

18,910

Solution 1

As Dennis Traub has pointed out, the overload of Aggregate you are using throws that exception when the source sequence is empty.

The obvious fix is to use the other overload of Aggregate that accepts an initial seed (you want string.Empty), but that would result in a leading comma in the result which you'll have to get rid of.

(EDIT: You can dodge this with .DefaultIfEmpty(string.Empty) followed by your existing Aggregate overload. This wouldn't produce a leading comma.)

In any case, using Aggregate like that to join strings isn't a great idea (produces a Schlemiel the Painter's algorithm). Here's how I would write the query:

allNames = string.Join(",", StockCollection.Select(s => s.Name)
                                           .Where(name => name.StartsWith("A"));

In .NET 3.5, you'll need a .ToArray() to materialize the Where results into an array.

Solution 2

Use with empty seed.

new string[]{}.Aggregate("", (a,b)=> a+b )

Solution 3

Using Aggregate(func) on an empty source throws an InvalidOperationException.

See documentation: http://msdn.microsoft.com/en-us/library/bb548651.aspx

Share:
18,910

Related videos on Youtube

D J
Author by

D J

SOreadytohelp

Updated on June 02, 2022

Comments

  • D J
    D J almost 2 years

    I am not using Single in LINQ below, but I am still getting a 'Sequence contains no elements' exception:

    allNames = StockCollection.Where((s) => s.Name.IndexOf("A") == 0)
                              .Select((s) => s.Name)
                              .Aggregate((namesInfo, name) => namesInfo += ", " + name);
    

    This exception comes when there is no stock starting with name 'A'.

    It seems that one extension method is expecting atleast one element satisfying the condition but that's not expected.

    Can you please suggest the best solution to resolve this?

    Thanks in advance.

  • D J
    D J over 12 years
    Thanks a lot for reply i am going to try this now.. But still i want to know why aggregate is throwing an exception.
  • Ani
    Ani over 12 years
    @D J: Why? What sensible value could it return? Perhaps the default value of the return type (null in this case), but I wouldn't want that.
  • D J
    D J over 12 years
    Problem is like we dont know at the runtime our collection will have any object or not? so it should not throw an exception or it can just return default value.
  • Myster
    Myster over 10 years
    +1 for DefaultIfEmpty this works well with examples more complex than strings.
  • Neil Vass
    Neil Vass almost 10 years
    If I could, I'd give you a second upvote for for the "in .NET 3.5" tip - thanks!
  • Nikita
    Nikita almost 4 years
    I think, that instead of "" should use string.Empty