在C#中,一种方法给我两个日期之间的月和年的列表

在C#中,一种方法给我两个日期之间的月和年的列表,c#,C#,你能帮我学一下这个方法吗。 我想要一个日期和当前月份之间的月和年的列表。 例如,从2016年10月23日起,结果是: 2016年10月 2016年11月 2016年12月 2017年1月 2017年2月 2017年3月 2017年4月 2017年5月 非常感谢,Dia此功能将完成此操作。它返回的是一系列日期-每个月的第一天,这是范围的一部分 public IEnumerable<DateTime> GetMonths(DateTime startDate, DateTime endD

你能帮我学一下这个方法吗。 我想要一个日期和当前月份之间的月和年的列表。 例如,从2016年10月23日起,结果是: 2016年10月 2016年11月 2016年12月 2017年1月 2017年2月 2017年3月 2017年4月 2017年5月


非常感谢,Dia

此功能将完成此操作。它返回的是一系列日期-每个月的第一天,这是范围的一部分

public IEnumerable<DateTime> GetMonths(DateTime startDate, DateTime endDate)
{
    if(startDate > endDate) 
    {
        throw new ArgumentException(
            $"{nameof(startDate)} cannot be after {nameof(endDate)}");
    }
    startDate = new DateTime(startDate.Year, startDate.Month, 1);
    while (startDate <= endDate)
    {
        yield return startDate;
        startDate = startDate.AddMonths(1);
    }
}
例如,如果参数为2016年2月7日和2016年4月2日,它将返回
2016年2月1日
2016年3月1日

2016年4月1日

您尝试过什么?提示:有一个
AddMonths()
方法,
DateTime
对象是可比较的。
var months = GetMonths(startDate, endDate);