我有一个查询,它计算一系列日期,我想运行一个不同的查询,只返回年/月组合。我无法弄清楚如何最好地实现这一点。
private IEnumerable<DateTime> MonthsWithItineraryData (int Id) // shipId
{
var months = (from i in context.Itineraries
join isd in context.ItineraryStartDates on i.Id equals isd.ItineraryId
join id in context.ItineraryDay on i.Id equals id.ItineraryId
where i.ShipId == Id
select (DateTime)DbFunctions.AddDays(isd.Date, id.Day)
);
return (months);
}
答案 0 :(得分:1)
我想你想要这样的东西:
return monts.GroupBy(x => new {x.Month, x.Year})
.Select(x => x.First());
答案 1 :(得分:0)
或者你可以将自定义相等比较器作为唯一参数:
public class DateTimeComparer : IEqualityComparer<DateTime>
{
public bool Equals(DateTime x, DateTime y)
{
return x.Year == y.Year && x.Month == y.Month;
}
public int GetHashCode(DateTime obj)
{
return obj.Year * 100 + obj.Month;
}
}
result = months.Distinct(new DateTimeComparer()).ToList();