private (DateTime startTime, string dateFormat) GetDateRangeAndFormat(int type, DateTime now, List<string> timePoints, int graphType = 1)
{
DateTime startTime;
string dateFormat;
switch (type)
{
case 1: // 月
startTime = now.AddMonths(-11);
dateFormat = "%Y-%m";
AddTimePoints(timePoints, 12, i => now.AddMonths(-i).ToString("yyyy-MM"));
timePoints.Sort((x, y) => DateTime.ParseExact(x, "yyyy-MM", null).CompareTo(DateTime.ParseExact(y, "yyyy-MM", null)));
break;
case 2: // 周
startTime = now.AddDays(-6);
dateFormat = "%Y-%m-%d";
AddTimePoints(timePoints, 7, i => now.AddDays(-i).ToString("yyyy-MM-dd"));
timePoints.Sort((x, y) => DateTime.ParseExact(x, "yyyy-MM-dd", null).CompareTo(DateTime.ParseExact(y, "yyyy-MM-dd", null)));
break;
case 3: // 日
startTime = now.Date;
dateFormat = "%H";
if (graphType == 1)
{
AddTimePoints(timePoints, 12, i => $"{now.Date.AddHours(i * 2):HH}-{now.Date.AddHours(i * 2 + 2):HH}");
}
else if (graphType == 0)
{
AddTimePoints(timePoints, 24, i => now.Date.AddHours(i).ToString("HH"));
}
timePoints.Sort((x, y) => int.Parse(x.Split('-')[0]).CompareTo(int.Parse(y.Split('-')[0])));
break;
default:
throw new ArgumentException("Invalid type value");
}
return (startTime, dateFormat);
}
// 添加时间点的辅助方法
private void AddTimePoints(List<string> timePoints, int count, Func<int, string> timePointGenerator)
{
for (int i = 0; i < count; i++)
{
timePoints.Add(timePointGenerator(i));
}
}
时:00 - 02 - 04 -……-18 - 20- 22- 00
日:2025-01-10 -2025-01-16
月:2024-02 - 2024-08 - 2025-01
遇到问题:
小时排序时,每次都是从10点开始排序 10 11 ……23 …… 00 01 02 03 04 05 06 07 08 09
我是用Dictionary存的数组会出现这个问题,经过各种办法使用Dictionary排序依然是这个问题,有可能是Dictionary内部排序导致的,
未解决更换成了List<KeyValuePair<string,List<>>>后排序正常。