I'm new to linq so would appreciate your help with getting this left join query to work.
I have "List hours" (a list of hours 0-23) that I'd like to left join with "var hourlyData" (a processed linq query containing aggregated data). My attempt at the left join is "var reportData".
DataSet ds = GetDataSet(sSql);
var stats = ds.Tables[0].AsEnumerable();
var hourlyData = from stat in stats
group stat by stat.Field<int>("Hour") into g
select new
{
Hour = g.Key,
Value = g.Key.ToString(),
D1 = g.Sum(stat => stat.Field<int>("D1")),
D2 = g.Sum(stat => stat.Field<int>("D2")),
D3 = g.Sum(stat => stat.Field<decimal>("D3"))
};
List<int> hours = new List<int>();
for (int i = 0; i < 24; i++)
{
hours.Add(i);
}
var reportData = from hour in hours.AsEnumerable()
join stat in hourlyData.AsEnumerable()
on hour equals stat.Hour
into sts2
from stat2 in sts2.DefaultIfEmpty()
select new
{
Hour = hour,
Value = hour,
D1 = stat2.D1 != null ? stat2.D1 : 0,
D2 = stat2.D2 != null ? stat2.D2 : 0,
D3 = stat2.D3 != null ? stat2.D3 : 0
};
The code above produces this error:
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 135: into sts2
Line 136: from stat2 in sts2.DefaultIfEmpty()
Line 137: select new
Line 138: {
Line 139: Hour = hour,
...
Thanks!
2 <>h__TransparentIdentifier0, <>f__AnonymousType05 stat2) in System.Linq.<SelectManyIterator>d__313.MoveNext() +303 System.Collections.Generic.List1..ctor(IEnumerable1 collection) +327 System.Linq.Enumerable.ToList(IEnumerable1 source) +58AsEnumerable()calls except for on the datatable for readability and your hours setup could simply bevar hours=Enumerable.Range(0,24)