gpt4 book ai didi

c# - 将连续日期组合成范围

转载 作者:行者123 更新时间:2023-11-30 13:57:50 26 4
gpt4 key购买 nike

我有一个对象列表

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

我希望能够创建一个新对象列表

public class sampleWithIntervals
{
public DateTime startDate;
public DateTime endDate;
public string content;
}

示例对象应根据内容分组到区间内。间隔只能包括原始样本列表中包含的那些日期。我不知道如何在 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 方法:

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 执行此操作,使用一种技巧,即按日期对项目进行分组减去索引以对连续项目进行分组:

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

关于c# - 将连续日期组合成范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19433189/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com