I have the following EF query that returns a list of usage data on only the days present in the DB.
var DailyUsage = context.UsageData.Where(u => u.UserID == CurrentUser.ID && u.Date >= Start && u.Date <= End)
.Select(p => new PerfData
{
Date = p.Date,
Transfers = p.Transfers,
Exists = p.Exists,
Duration = p.Duration
}).ToList();
I'd like it to return a list with an uninterrupted date sequence with data points at 0 for inexistent dates in the DB so I am trying to do a left outer join with the following list of dates but can't seem to get it right:
public static List<DateTime> GetDateRange(DateTime startingDate, DateTime endingDate)
{
if (StartingDate > EndingDate)
{
return null;
}
List<DateTime> rv = new List<DateTime>();
DateTime tmpDate = startingDate;
do
{
rv.Add(tmpDate);
tmpDate = tmpDate.AddDays(1);
}
while (tmpDate <= endingDate);
return rv;
}
If I understand correctly and the list of DateTimes is the outer part of the join, you can use the join into
clause to perform a left outer join .
var dailyUsages = context.UsageData
.Where(u => u.UserID == CurrentUser.ID &&
u.Date >= start &&
u.Date <= end)
.Select(p => new PerfData()
{
Date = p.Date,
Transfers = p.Transfers,
Exists = p.Exists,
Duration = p.Duration
}).ToList();
var dates = (from date in GetDateRange(start, end)
join dailyUsage in dailyUsages on date equals dailyUsage.Date into grp
from item in grp.DefaultIfEmpty(new PerfData()
{
Date = date,
Transfers = 0,
Exists = 0,
Duration = 0
})
select item).ToList();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.