c# - 使用 linq group by 从具有 DateTime 属性的对象列表获取具有间隔 StartDate、EndDate 的列表

标签 c# linq group-by

我有一个按天存储数据的预订实体,基于此我希望能够创建另一个列表,如果第一个列表中的日期是连续的,则按间隔(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)}
        };

最佳答案

为此,您可以将 GroupBySelectManyAggregate 结合使用:

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;
}

关于c# - 使用 linq group by 从具有 DateTime 属性的对象列表获取具有间隔 StartDate、EndDate 的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18716766/

相关文章:

c# - 尝试将文件从 UWP 应用程序上传到 Flask restful web api,失败

c# - Emgu cv 将 CircleF 保存为图像

c# - 从 IList<object_type> 获取 IList<field_type>

group-by - 如何使用hbase协处理器实现groupby?

c# - 具有动态列组的 LINQ GroupBy

c# - 设置透明色

c# - for循环中的sql

linq - 具有分离条件的 NHibernate Query<T>...

c# - `KeyValuePair<string, int>` 的默认值是多少?

mysql - 过滤掉MySQL中使用GROUP BY得到的结果