I have this collection of GroupedResult
IQueryable<GroupedResult> groupedResult = from p in db.Departure
group p by new { p.Terminal, p.DepartureDate, p.DepartureDate.Month } into g
select new GroupedResult
{
terminal = g.Key.Terminal.Code,
date = g.Key.DepartureDate,
distance = g.Count(),
month = g.Key.Month
};
The problem is that the collection I get has some dates missing. For example db.Departure contains Feb. 1, 2, 4, and 6. I also wanted to show GroupedResult
for Feb. 3 and 5 so I use the following code to create a collection of dates starting from a particular start date:
var dates = new List<DateTime>();
for (var dt = date; dt <= DateTime.Now; dt = dt.AddDays(1))
{
dates.Add(dt);
}
And then join dates
with groupedResult
var result = from p in groupedResult.ToList()
from q in dates.Where(r => r == p.date).DefaultIfEmpty()
select p;
The result I get is same as the one with groupedResult
. How can I also show the entries with no date data?
This is because you are selecting P at the very end.....you have to create new anonymous class
var result = from q in dates
join p in groupedResult.ToList() on q equals p.date into joinedResult
from r in joinedResult.DefaultIfEmpty()
select new
{
terminal = r==null?null:r.terminal,
date = q,
distance = r==null?null:r.distance,
month = r==null?null:r.month
};
var result = from p in groupedResult.ToList()
from q in dates.Where(r => r == p.date).DefaultIfEmpty()
select p;
You've got the left join the wrong way around. You're selecting all items from your groupedResult
and then ask LINQ to get all dates - or none if there is none - that match a date that already exists in the groupedResult
.
var result = from q in dates
from p in groupedResult.Where(r => r.date == q).DefaultIfEmpty()
select new { Date = q, Items = p };
This works, because you select all dates and search for matching grouped items instead.
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.