I am trying to replicate the below SQL in C# & Linq , but I am not too experienced with Linq beyond the basics.
SELECT SUM(coalesce(cd.minutesspent,0))
FROM timelabels t
LEFT JOIN challengedetails cd on cd.createddate = t.date
GROUP BY t.date
This would give me a sum of minutes for every date, or zero if there were null entries. Pretty straightforward I think.
// timelabels structure
DateTime start = DateTime.Now.AddDays(-14);
DateTime end = DateTime.Now;
List<DateTime> timelabels = new List<DateTime>();
for (var dt = start; dt <= end; dt = dt.AddDays(1))
{
timelabels.Add(dt);
}
// ChallengeDetails structure & sample data
class ChallengeDetails(){
DateTime? Createddate
int? MinutesSpent
}
List<ChallengeDetails> ChallengeDetails = new List<ChallengeDetails >();
List<ChallengeDetails> ChallengeDetails = new List<ChallengeDetails>();
ChallengeDetails.Add(new ChallengeDetails { MinutesSpent = 44, Createddate = DateTime.Now.AddDays(-10) });
ChallengeDetails.Add(new ChallengeDetails { MinutesSpent = 31, Createddate = DateTime.Now.AddDays(-7) });
ChallengeDetails.Add(new ChallengeDetails { MinutesSpent = 13, Createddate = DateTime.Now.AddDays(-3) });
ChallengeDetails.Add(new ChallengeDetails { MinutesSpent = 77, Createddate = DateTime.Now.AddDays(-2) });
// The Actual Code
List<string> timedata = (from a in timelabels
join al in ChallengeDetails on a equals al.Createddate into All
from al in All.DefaultIfEmpty()
group al by a into grouped
select grouped.Sum(m => m.MinutesSpent ?? 0).ToString()
).ToList();
Looking at this it should work - I have DefaultIfEmpty which should replicate the left join. Within the Sum I have '?? 0' which should be the fallback for any dates that dont have a ChallengeDetail.
But I get System.NullReferenceException: 'Object reference not set to an instance of an object.' m was null. I shouldnt have gotten this as I have null entries covered or have I got this all wrong ?