简体   繁体   中英

linq max and min date

I am having some problems porting this SQL SP into a linq statement. The sql logic is basic get the min and max StartDate and if they are equal use the min date value for MeetingDate. MeetingDate is a string so I would tostring it MM/dd/yyyy. If they are not equal then concat both min StartDate and max StartDate together.

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

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. If you want the output how you have it then converting to a string would probably be the best choice. Rough untested example below. I have updated my answer to use the correct LINQ syntax. 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());

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.

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