简体   繁体   English

LINQ日期左外联接不起作用

[英]LINQ left outer join on date not working

I have this collection of GroupedResult 我有这个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: 例如db.Departure包含2月1日,2月4日和6日。我还想显示2月3日和5日的GroupedResult ,因此我使用以下代码创建从特定开始日期开始的日期集合:

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 然后使用groupedResult加入dates

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 . 我得到的结果与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 这是因为您最终选择了P .....您必须创建新的匿名类

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 . 您正在从groupedResult选择所有项目,然后要求LINQ获取与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. 之所以有效,是因为您选择了所有日期,然后搜索匹配的分组项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM