確定有人會想出一個整潔的LINQ解決方案,但這裏是我的舊式解決方案。當然它有問題,不會與每個組合應對,拼湊起來,解決了這一問題,但以任何方式:-(
internal class SourceData
{
public int TypeId { get; set; }
public DateTime Date { get; set; }
}
internal class Result
{
public int TypeId { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
class Program
{
static void Main()
{
var a = new List<SourceData> {
new SourceData {TypeId = 1, Date = new DateTime(2010, 02, 01)},
new SourceData {TypeId = 1, Date = new DateTime(2010, 02, 02)},
new SourceData {TypeId = 1, Date = new DateTime(2010, 02, 03)},
new SourceData {TypeId = 2, Date = new DateTime(2010, 02, 03)},
new SourceData {TypeId = 2, Date = new DateTime(2010, 02, 04)},
new SourceData {TypeId = 2, Date = new DateTime(2010, 02, 06)}
};
var results = new List<Result>();
int currentTypeId = 1;
var rangeEndDate = new DateTime();
DateTime rangeStartDate = a[0].Date;
DateTime currentDate = a[0].Date;
for (int i = 1; i < a.Count() ; i++)
{
if (a[i].TypeId != currentTypeId)
{
results.Add(new Result() { TypeId = currentTypeId, StartDate = rangeStartDate, EndDate = rangeEndDate });
currentTypeId += 1;
rangeStartDate = a[i].Date;
}
TimeSpan tSpan = a[i].Date - currentDate;
int differenceInDays = tSpan.Days;
if(differenceInDays > 1)
{
results.Add(new Result { TypeId = currentTypeId, StartDate = rangeStartDate, EndDate = a[i-1].Date });
rangeStartDate = a[i].Date;
}
rangeEndDate = a[i].Date;
currentDate = a[i].Date;
}
results.Add(new Result { TypeId = currentTypeId, StartDate = rangeStartDate, EndDate = rangeEndDate });
Console.WriteLine("Output\n");
foreach (var r in results)
Console.WriteLine(string.Format("{0} - {1} - {2}",r.TypeId,r.StartDate.ToShortDateString(),r.EndDate.ToShortDateString()));
Console.ReadLine();
}
}
不優雅提供了以下的輸出: -
輸出
1 - 01/02/2010 - 03/02/2010
2 - 03/02/2010 - 04/02/2010
2 - 06/02/2010 - 06/02/2010
你如何確定開始和結束日期是什麼? – skyfoot 2010-07-02 08:55:35
@skyfoot開始和結束日期是在初始數據中找到的任何日期範圍的開始和結束。 – RYFN 2010-07-02 09:10:26
但不應該是「01/02/2010至03/02/2010」和「03/02/2010至06/02/2010」 – skyfoot 2010-07-02 10:14:48