Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequence contains no elements exception in linq without even using Single

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.

like image 940
D J Avatar asked Jan 15 '12 06:01

D J


People also ask

How do you solve a sequence that has no elements?

When you get the LINQ error "Sequence contains no elements", this is usually because you are using the First() or Single() command rather than FirstOrDefault() and SingleOrDefault() .

What is the difference between FirstOrDefault and SingleOrDefault?

SingleOrDefault() – Same as Single(), but it can handle the null value. First() - There is at least one result, an exception is thrown if no result is returned. FirstOrDefault() - Same as First(), but not thrown any exception or return null when there is no result.

What is FirstOrDefault C#?

FirstOrDefault<TSource>(IEnumerable<TSource>, TSource) Returns the first element of a sequence, or a specified default value if the sequence contains no elements. FirstOrDefault<TSource>(IEnumerable<TSource>) Returns the first element of a sequence, or a default value if the sequence contains no elements.


1 Answers

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.

like image 52
Ani Avatar answered Sep 18 '22 08:09

Ani