Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ aggregate sequence contains no elements

Tags:

c#

linq-to-sql

I'm dynamically building up a query starting with this:

var items = db.Items;

...

case "4":
items = items.OrderBy(x => x.Ratings.Average(t => t.score)).ThenBy(x => x.title);

The problem is that some items don't have any data in the ratings table yet, so I believe it's trying to average over data that doesn't exist. Using DefaultOrEmpty() at the end doesn't seem to have any effect. Any suggestions on how I would fix this?

like image 421
The Muffin Man Avatar asked May 28 '11 14:05

The Muffin Man


2 Answers

If you are using this form:

var effectiveFloor = 
   policies
   .Where(p => p.PricingStrategy == PricingStrategy.EstablishFloor)
   .Max(p => p.Amount);

Then the solution is:

var effectiveFloor = 
    policies
    .Where(p => p.PricingStrategy == PricingStrategy.EstablishFloor)
    .DefaultIfEmpty()
    .Max(p => p==null ? 0 : p.Amount);

Found here

like image 200
DShook Avatar answered Nov 12 '22 10:11

DShook


   items = items.Where(x=>x.Ratings.Any()).
           OrderBy(x => x.Ratings.Average(t => t.score)).
           ThenBy(x => x.title);

Try that.

like image 33
AD.Net Avatar answered Nov 12 '22 11:11

AD.Net