3

我有一个按天存储数据的预订实体,基于此,如果第一个列表中的日期是连续的,我希望能够创建另一个按间隔(StartDate,EndDate)存储数据的列表,并且分组应该是基于对 { VenueId, TimePeriodId}。任何想法表示赞赏。

public class BookedRoom
{       
    public int VenueId { get; set;}        
    public int TimePeriodId { get; set; }        
    public DateTime Day { get; set; }        
}

 public class EventSetup
 {
    public int VenueId { get; set; }        
    public int TimePeriodId { get; set; }        
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }       
 }

List<BookedRoom> bookedRooms = new List<BookedRoom>(){
            new BookedRoom { VenueId = 1, TimePeriodId = 1, Day = new DateTime(2013, 9, 1)},
            new BookedRoom { VenueId = 1, TimePeriodId = 1, Day = new DateTime(2013, 9, 2)},
            new BookedRoom { VenueId = 2, TimePeriodId = 2, Day = new DateTime(2013, 9, 3)},
            new BookedRoom { VenueId = 1, TimePeriodId = 1, Day = new DateTime(2013, 9, 4)}
        };


        // Some Linq to process bookedRooms and obtain a list which I can use to do the following:

        List<EventSetup> setups = new List<EventSetup>()
        {
            new EventSetup{ VenueId =1, TimePeriodId = 1, StartDate=new DateTime(2013, 9, 1), EndDate = new DateTime(2013, 9, 2)},
            new EventSetup{ VenueId =2, TimePeriodId = 2, StartDate=new DateTime(2013, 9, 3), EndDate = new DateTime(2013, 9, 3)},
            new EventSetup{ VenueId =1, TimePeriodId = 1, StartDate=new DateTime(2013, 9, 4), EndDate = new DateTime(2013, 9, 4)}
        };
4

1 回答 1

2

您可以与和GroupBy结合使用:SelectManyAggregate

var setups =
    bookedRooms.GroupBy(x => Tuple.Create(x.TimePeriodId, x.VenueId))
               .SelectMany(x => x.Aggregate(
                                    new List<EventSetup>(), AccumulateRooms))
               .OrderBy(x => x.StartDate)
               .ToList();

List<EventSetup> AccumulateRooms(List<EventSetup> existingSetups,
                                 BookedRoom currentRoom)
{
    var setup = existingSetups.LastOrDefault();
    if(setup == null || setup.EndDate.AddDays(1) != currentRoom.Day.Date)
    {
        setup = new EventSetup
        {
            VenueId = currentRoom.VenueId,
            TimePeriodId = currentRoom.TimePeriodId,
            StartDate = currentRoom.Day.Date,
        };
        existingSetups.Add(setup);
    }
    setup.EndDate = currentRoom.Day.Date;
    return existingSetups;
}
于 2013-09-10T11:01:04.217 回答