Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq sum and null

Tags:

c#

asp.net

linq

sum

I have the query:

var qq = (from c in db.tblArcadeGames
        where
            c.IsDeleted == false &&
            c.ParentGameID == 0 &&
            c.Approved == true
        let aggPlays = c.Plays + db.tblArcadeGames.Where(v => v.ParentGameID == c.ID).Sum(v => (int?)v.Plays)
        orderby aggPlays descending
        select new { c, aggPlays })
        .Skip(Skip)
        .Take(Fetch);

foreach (var g in qq)
{
    HttpContext.Current.Response.Write("{" + g.aggPlays + "}\n");
}

When I print out aggPlays in the loop above they come out as:

{21}
{}
{}
{}

The problem seems to be that the Sum() returns null if no records exist. I'm not sure how to get around this so that c.Plays + null wont equal null but just c.Plays.

like image 973
Tom Gullen Avatar asked Dec 29 '11 02:12

Tom Gullen


2 Answers

You can correct this by not returning int?, but rather convert to an int directly:

.Sum(v => v.Plays ?? 0)
like image 151
Reed Copsey Avatar answered Nov 19 '22 01:11

Reed Copsey


    int response =
    (from p in data.tbHoraires
     where p.eid == eid && p.annee == annee && p.obligatoire == true
     select (int?)p.nbminute ?? 0).Sum();
like image 38
Pascal Carmoni Avatar answered Nov 19 '22 02:11

Pascal Carmoni