c#代码工具箱-数字范围合并
public class ScheduleWeekSpanModel { public int week_from { get; set; } public int week_to { get; set; } }
//分割,例如 1;2;3;5;7;8;10;11;12;15 public static List<ScheduleWeekSpanModel> GetWeekSpans(string weeks) { var weekList = weeks.Split(';').ToList().Select(item => Int32.Parse(item)).OrderBy(i=>i).ToList();//转成数字并排序 List<ScheduleWeekSpanModel> spans = new List<ScheduleWeekSpanModel>(); var week_from = 0;// for (var i = 0; i <= weekList.Count; i++) { if (weekList.Count == 1) { //只有一个元素 ScheduleWeekSpanModel obj = new ScheduleWeekSpanModel { week_from = weekList[i], week_to = weekList[i] }; spans.Add(obj); break; } if (week_from == 0) { week_from = weekList[i]; } if (i + 1 == weekList.Count) { //最后一个元素 ScheduleWeekSpanModel obj = new ScheduleWeekSpanModel { week_from = week_from, week_to = weekList[i] }; spans.Add(obj); break; } if (weekList[i] == weekList[i + 1] - 1) { continue; } else { //不连续 ScheduleWeekSpanModel obj = new ScheduleWeekSpanModel { week_from = week_from, week_to = weekList[i] }; spans.Add(obj); //重新开始 week_from = 0; } } return spans; }
//例如 1;2;3;5;7;8;10;11;12;15显示为1-3;5;7-8;10-12;15 public string DisplayWeeks(string weeks) { if (String.IsNullOrEmpty(weeks)) return string.Empty ;
var weekSpans= GetWeekSpans(weeks); if (weekSpans == null || weekSpans.Count == 0) return string.Empty; //拼接输出 StringBuilder sb = new StringBuilder(); foreach(var weekspan in weekSpans) { if (weekspan.week_from == weekspan.week_to) { sb.Append(weekspan.week_from); sb.Append("; "); } else { sb.Append(weekspan.week_from); sb.Append("—"); sb.Append(weekspan.week_to); sb.Append("; "); } } return sb.ToString(); }