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