日期连贯计算
需求:从选中的日期列表中,合并日期连贯的日期,组成DateSpans对象的StartDate和EndDate属性,形成新的对象List<DateSpans>,代码和结果截图如下:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 5 namespace CalcDateRange 6 { 7 class Program 8 { 9 static void Main(string[] args) 10 { 11 List<DateSpans> lstDateSpans = new List<DateSpans>(); 12 13 //选中的日期列表 14 List<DateTime> dates = new List<DateTime> { 15 new DateTime(2017,9,2),new DateTime(2017,9,1),new DateTime(2017,9,5),new DateTime(2017,9,7) 16 ,new DateTime(2017,9,8),new DateTime(2017,9,8) 17 }; 18 19 //把日期按从小到大排序 20 dates = dates.OrderBy(p => p.Date).ToList(); 21 22 if (dates.Count > 0) 23 { 24 Dictionary<DateTime, DateTime> timeSpans = new Dictionary<DateTime, DateTime>(); 25 DateTime previous = DateTime.MinValue; 26 DateTime current = DateTime.MinValue; 27 DateTime currentKey = dates[0]; 28 DateSpans ds = new DateSpans(); 29 30 for (int i = 0; i < dates.Count; i++) 31 { 32 if (!timeSpans.ContainsKey(currentKey)) 33 { 34 timeSpans.Add(currentKey, DateTime.MinValue); 35 } 36 if (i > 0) 37 { 38 previous = dates[i - 1]; 39 } 40 current = dates[i]; 41 if (previous != DateTime.MinValue && current.Subtract(previous).Days > 1) 42 { 43 timeSpans[currentKey] = previous; 44 currentKey = current; 45 timeSpans.Add(currentKey, DateTime.MinValue); 46 } 47 48 if (i == dates.Count - 1) 49 { 50 timeSpans[currentKey] = current; 51 } 52 } 53 if (timeSpans.Count > 0) 54 { 55 foreach (var item in timeSpans) 56 { 57 ds = new DateSpans(); 58 ds.StartDate = item.Key; 59 ds.EndDate = item.Value; 60 lstDateSpans.Add(ds); 61 62 Console.WriteLine(string.Format("Start Date:{0} End Date:{1}", item.Key.ToShortDateString(), item.Value.ToShortDateString())); 63 } 64 } 65 } 66 67 Console.ReadKey(); 68 } 69 70 class DateSpans 71 { 72 public DateTime StartDate { get; set; } 73 public DateTime EndDate { get; set; } 74 } 75 } 76 }
运行结果:

作者:Gerry Ge
出处:https://www.cnblogs.com/gerryge/p/7472514.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
转载请注明出处
分类:
C#
标签:
Date Range
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构