将连续日期组合成范围 [英] Combining consecutive dates into ranges
本文介绍了将连续日期组合成范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个对象列表
public class sample
{
public DateTime Date;
public string content;
}
我希望能够创建一个新对象列表
I want to be able to create a list of new objects
public class sampleWithIntervals
{
public DateTime startDate;
public DateTime endDate;
public string content;
}
样本对象应根据内容分组.间隔只能包括原始样本列表中包含的那些日期.我不知道如何在 Linq 中执行此操作.
The sample objects should be grouped into intervals based on the content. The intervals can include only those dates that are included in the original sample list. I dont know how to do this in Linq.
示例数据:
{"10/1/2013", "x"}
{"10/2/2013", "x"}
{"10/2/2013", "y"}
{"10/3/2013", "x"}
{"10/3/2013", "y"}
{"10/10/2013", "x"}
{"10/11/2013", "x"}
{"10/15/2013", "y"}
{"10/16/2013", "y"}
{"10/20/2013", "y"}
This should give me
{"10/1/2013","10/3/2013", "x"}
{"10/2/2013","10/3/2013", "y"}
{"10/10/2013","10/11/2013", "x"}
{"10/15/2013","10/16/2013", "y"}
{"10/20/2013","10/20/2013", "y"}
推荐答案
这是一种非 Linq 方法:
Here's a non-Linq way to do it:
List<sampleWithIntervals> groups = new List<sampleWithIntervals>();
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;
}
}
您可以使用 Linq 使用一种技巧来完成此操作,该技巧按日期减去索引对项目进行分组以对连续项目进行分组:
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
})
这篇关于将连续日期组合成范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文