Combining consecutive dates into ranges

后端 未结 2 470
悲哀的现实
悲哀的现实 2020-12-18 12:44

I have a List of objects

public class sample
{
 public DateTime Date;
 public string content;
}

I want to be able to create a list of new o

2条回答
  •  借酒劲吻你
    2020-12-18 13:02

    Here's a non-Linq way to do it:

    List groups = new List();  
    sampleWithIntervals curGroup = null;
    
    foreach(sample s in samples.OrderBy(sa => sa.content).ThenBy(sa => sa.Date))
    {
        if(curGroup == null || // first group
            s.Date != curGroup.endDate.AddDays(1) ||
            s.content != curGroup.content   // new group
          ) 
        {
            curGroup = new sampleWithIntervals() {startDate = s.Date, endDate = s.Date, content = s.content};
            groups.Add(curGroup);
        }
        else
        {
            // add to current group
            curGroup.endDate = s.Date;
        }
    }
    

    You can do this with Linq using a trick that groups the items by the date minus the index to group consecutive items:

    samples.OrderBy(s => s.content)   
           .ThenBy(s => s.Date)
           // select each item with its index
           .Select ((s, i) => new {sample = s, index = i})  
           // group by date miuns index to group consecutive items
           .GroupBy(si => new {date = si.sample.Date.AddDays(-si.index), content = si.sample.content})  
           // get the min, max, and content of each group
           .Select(g => new sampleWithIntervals() {
                            startDate = g.Min(s => s.sample.Date), 
                            endDate = g.Max(s => s.sample.Date), 
                            content = g.First().sample.content
                            })
    

提交回复
热议问题