Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
892 views
in Technique[技术] by (71.8m points)

c# - Get a List of Dates In a Date Range

Say I have a list of LockedDate.

A LockedDate has a DateTime and an IsYearly bool. If IsYearly is true then the year should not be considered because it could be any year. Time should never be considered.

Ex: X-Mas, Dec 25 is yearly.

Now I have a List of LockedDate.

There are no duplicates.

Now I need this function:

This function will do: If a LockedDate is NOT yearly and the day, month, and year are within the range from source, add to return list.

If a LockedDate IS yearly, and its month / day fall in the range, then add a new date for each year in the range.

Say I have Dec 25 with IsYearly as true. My range is Jan 22 2013 to Feb 23 2015 inclusive. would need to add Dec 25 2013 as a new date and Dec 25 2014 as a new Date to the list.

List<Date> GetDateRange(List<LockedDate> source, DateTime start, DateTime end)
{


}

Thanks

Dec 25 Yearly -> Dec 25 2013, Dec 25 2014
Dec 2, 2011  NOT Yearly -> Nothing
March 25, 2013 => March 25 2013
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This might give you at least an idea, it's not tested at all yet:

List<DateTime> GetDateRange(List<LockedDate> source, DateTime start, DateTime end)
{
    if (start > end)
        throw new ArgumentException("Start must be before end");

    var ts = end - start;
    var dates = Enumerable.Range(0, ts.Days)
        .Select(i => start.AddDays(i))
        .Where(d => source.Any(ld => ld.Date == d
            || (ld.IsYearly && ld.Date.Month == d.Month && ld.Date.Day == d.Day)));
    return dates.ToList();
}

Update Here's the demo with your sample data, it seems to work: http://ideone.com/3KFi97


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...