简体   繁体   English

linq 最大和最小日期

[英]linq max and min date

I am having some problems porting this SQL SP into a linq statement.我在将此 SQL SP 移植到 linq 语句时遇到了一些问题。 The sql logic is basic get the min and max StartDate and if they are equal use the min date value for MeetingDate. sql 逻辑是获取最小和最大 StartDate 的基本逻辑,如果它们相等,则使用 MeetingDate 的最小日期值。 MeetingDate is a string so I would tostring it MM/dd/yyyy. MeetingDate 是一个字符串,所以我将它串起来 MM/dd/yyyy。 If they are not equal then concat both min StartDate and max StartDate together.如果它们不相等,则将 min StartDate 和 max StartDate 连接在一起。

LINQ
    var Meeting = (from m in db.Meetings
    join md in db.MeetingDates on m.MeetingId equals md.MeetingId
    join mf in db.MeetingFiles on m.MeetingId equals mf.MeetingId
    join fm in db.FileManagers on mf.FileManagerId equals fm.FileManagerId
    join vwGP in db.vwGuidelinePanels on m.GroupId equals vwGP.GroupId
    where mf.FileCategoryItemDictionaryId == 755
    select new Model.Meeting
    {
    MeetingId = m.MeetingId,
    GroupId = m.GroupId,
    MeetingDate =  max(md.StartDate) == min(md.StartDate)? min(md.StartDate)
    min(md.StartDate) + ' - ' + max(md.StartDate)
    }).ToList();


SQL
    case 
        when Convert(varchar(10),min(md.StartDate),101)=Convert(varchar(10),max(md.StartDate),101) 
        then Convert(varchar(10),min(md.StartDate),101) 
    else 
    Convert(varchar(10),min(md.StartDate),101)+' - '+Convert(varchar(10),max(md.StartDate),101) end

output output

04/15/2010
05/06/2010
05/12/2010
06/13/2010 - 06/16/2010
06/16/2010 - 06/19/2010

using the max and min there is a runtime error使用最大值和最小值存在运行时错误

在此处输入图像描述

One issue is min(md.StartDate) would be a DateTime type and the subtraction of min(md.StartDate) + ' - ' + max(md.StartDate) would be a TimeSpan type.一个问题是min(md.StartDate)将是DateTime类型,而min(md.StartDate) + ' - ' + max(md.StartDate)的减法将是TimeSpan类型。 If you want the output how you have it then converting to a string would probably be the best choice.如果您想要 output 如何拥有它,那么转换为string可能是最佳选择。 Rough untested example below.下面是未经测试的粗略示例。 I have updated my answer to use the correct LINQ syntax.我已更新我的答案以使用正确的 LINQ 语法。 Yet again this is untested.再一次,这是未经测试的。

MeetingDate = md.StartDate.Max() == md.StartDate.Min()? md.StartDate.Min().ToString("MM/dd/yyyy") : string.Format("{0: MM/dd/yyyy} - {1: MM/dd/yyyy}", md.StartDate.Min(), md.StartDate.Max());

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

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