所以你被一系列对象困住了,其中每个对象都有一个类型为 string 的 Date 属性,格式为 yyyyMM。并且您想从中提取一些数据。
您的日期格式与语言无关。不管你的电脑是英国的还是中国的。 Date 属性将始终采用 yyyyMM 格式。
这使得将其转换为 DateTime 格式变得相当容易,从而可以轻松访问年份和月份。
const string dateTimeFormat = "yyyyMM";
CultureInfo provider = CultureInfo.InvariantCulture;
var dateList = ... // your original list of items with the string Date property
var itemsWithYearMonth = dateList.Select(item => new
{
DateTime = DateTime.ParseExact(item, dateTimeFormat, provider)
... // select other items you need for your bar chart
});
现在,给定一个 StartYear/Month、一个 NrOfYears 和一个 NrOfMonths,您希望将 dateTimeItems 分组到同一月份的组中。
例如,从 2018-11 年开始,我想要四个月的小组,连续三年(是的,是的,我知道在你最初的要求中只有 3 个月、2 年,但为什么要限制自己,让我们让您的代码可重用):
group 1: 2018-11, 2019-11, 2020-11, 2021-11
group 2: 2018-12, 2019-12, 2020-12, 2021-12
group 3: 2019-01, 2020-01, 2021-01, 2022-01
奖励积分:我们将通过年限!
所以输入:
var itemsWithYearMonth = ... // see above
int startYear = ...
int startMonth = ...
int nrOfMonths = ...
int nrOfYears = ...
我们将制作具有相同月份的物品组。我们不想要一年中的所有月份,我们只想要几个月。如果我们想要从第 11 个月开始的 3 个月,我们需要保留第 11、12、1 个月的组。
var desiredMonths = Enumerable.Range(startMonth, nrOfMonths) // example: 11, 12, 13
.Select(monthNr => 1 + ((monthNr-1) % 12)); // 11, 12, 1
根据您的输入,我们不想要所有月份,我们只想要比起始月份大的年/月。
DateTime startMonth = new DateTime(startYear, startMonth, 1);
最简单的方法是只保留日期等于或大于 startMonth 的项目的输入源,并且只取每个组的第一个 NumberOfYears 项目。这样,如果您像我在示例中所做的那样通过年份边界,您将获得正确数量的项目。
var result = itemsWithYearMonth
// keep only the items newer than startMonth
.Where(item => item.DateTime >= startMonth)
// group by same month:
.GroupBy(item => item.DateTime.Month,
(month, itemsWithThisMonth) => new
{
Month = month, // in my example: 11, 12, 1, ...
// in every group: take the first nrOfYears items:
Items = itemsWithThisMonth
// order by ascending year
.OrderBy(itemWithThisMonth => itemWithThisMonth.Year)
// no need to order by Month, all Months are equal in this group
.Take(nrOfYears)
.ToList(),
})
// keep only the desired months:
.Select(group => desiredMonth.Contains(group.Month));
所以现在你有了组:
group of month 11, with data of years 2018, 2019, 2020, 2021
group of month 12, with data of years 2018, 2019, 2020, 2021
group of month 01, with data of years 2019, 2020, 2021, 2022