C # programming practices-help my wife calculate the maternity leave plan,
Summary
During lunch break at noon today, I chatted with my wife. My wife has to take maternity leave in a few days. She asked me on the Internet to help her count how to ask for leave, which is the most cost-effective, my wife is a person who will live. Of course, it is incumbent on me to face this kind of requirement, but my first response to this question is: how can we use data? As a result, I began to learn about the latest maternity leave policy regulations in Shanghai in 2014. The general situation is as follows: "The total number of maternity leave and late childbearing leave is 128 days.The previous 98 days were normal maternity leave, including national statutory holidays and weekends, The last 30 days is a late education holiday, which only includes a weekend, does not contain national statutory holidays, that is to say, the holiday will be postponed in the event of national statutory holidays ", pay attention to the bold description, we can see that the above careful calculation is reflected in the normal maternity leave of the previous 98 days. What we need to do is try to avoid regular maternity leave that contains too many national holidays. Otherwise, if we use our wife's words, it will be a "loss". Note that I will quote the word "loss, I mean we don't haveToo muchIf it is too much, it is easy to lose the interests of life and the freedom of mind. It is a blessing to say that suffering is a loss. However, without interfering with such conditions, we still have to work hard to get farther away. This problem is not complicated. So why should I be happy? Besides, I have been preparing to write blogs recently. I often read books, read articles, and read blogs. After all, I have to get a glimpse of the last word on the paper. I am sure I have to do this and I still need to practice it frequently, in addition, as a part of this line, we must have an open and sharing mentality. Well, there is already a lot of nonsense. We started to design and implement the Code.
Fields
Preliminary positioning: This is an application of Time query. The model is built around time, and the holiday is expressed by month and day number (Gregorian calendar and lunar calendar). You also need to provide holiday rule definitions as follows (DateModels. cs ):
Using System; using System. collections. generic; using System. globalization; using System. linq; using System. text; using System. threading. tasks; namespace HelloBaby {// The default Holiday set is provided here. The definition of public static class DefaultHoliday {// public static readonly Holiday NewYearsHoliday = new Holiday (MonthDayDate. newYearsDay, 1); // three days off during the Spring Festival. public static readonly Holiday SpringFestivalHoliday = new Holiday will be held from the previous day (new Year's Eve (MonthDayDate. springFestival,-1, 3); // 1-day public static readonly Holiday QingMingHoliday = new Holiday (MonthDayDate. qingMingDay, 1); // one-day Holiday on Labor Day public static readonly Holiday LabourHoliday = new Holiday (MonthDayDate. labourDay, 1); // Dragon Boat Festival 1 day Holiday public static readonly Holiday DragonBoatHoliday = new Holiday (MonthDayDate. dragonBoatFestival, 1); // one-day Mid-Autumn Festival Holiday public static readonly Holiday MidAutumnHolida Y = new Holiday (MonthDayDate. midAutumnDay, 1); // public static readonly Holiday NationalHoliday = new Holiday (MonthDayDate. nationalDay, 3); public static List <Holiday> Holidays = new List <Holiday> {defaulthoocs. newYearsHoliday, DefaultHoliday. springFestivalHoliday, DefaultHoliday. qingMingHoliday, defaulthoocs. labourHoliday, defaulthoocs. dragonBoatHoliday, defaulthoocs. midAutumnHoli Day, DefaultHoliday. NationalHoliday};} // holiday, which contains three members (lunar calendar or calendar day? A few days in advance? Public struct Holiday {public Holiday (MonthDayDate monthDay, int startOffset, int days): this () {MonthDay = monthDay; StartOffset = startOffset; Days = days ;} public Holiday (MonthDayDate monthDay, int days): this (monthDay, 0, days) {} public MonthDayDate MonthDay {get; private set;} public int StartOffset {get; set ;} public int Days {get; set;} // obtain the actual holiday date by year enumeration public IEnumerable <DateTime> ToDateTimeRange (int year) {DateTime gregorian = DateTime. now; if (MonthDay. calendar = CalendarKind. lunarCalendar) gregorian = DateUtility. convertLunarYearDate (
Year, MonthDay. month, MonthDay. day); else gregorian = new DateTime (year, MonthDay. month, MonthDay. day); DateTime begin = gregorian. addDays (StartOffset); for (int I = 0; I <Days; I ++) {yield return begin. addDays (double) I) ;}}// use the Calendar attribute here to differentiate calendars. // you can also change struct to class to use the inherited design method, convenient extension of public struct MonthDayDate {// new Year's Day public static readonly MonthDayDate NewYearsDay = new MonthDayDate (1, 1 );// China Spring Festival public static readonly MonthDayDate SpringFestival = new MonthDayDate (1, 1, CalendarKind. lunarCalendar); // Tomb Sweeping Day public static readonly MonthDayDate QingMingDay = new MonthDayDate (4, 5); // May Day public static readonly MonthDayDate LabourDay = new MonthDayDate (5, 1 ); // Dragon Boat Festival public static readonly MonthDayDate DragonBoatFestival = new MonthDayDate (5, 5, CalendarKind. lunarCalendar); // Mid-Autumn Festival publ Ic static readonly MonthDayDate MidAutumnDay = new MonthDayDate (8, 15, CalendarKind. lunarCalendar); // National day public static readonly MonthDayDate NationalDay = new MonthDayDate (10, 1); public MonthDayDate (int month, int day, CalendarKind calendar AR): this () {Month = month; Day = day; Calendar = calendar;} public MonthDayDate (int month, int day): this (month, day, CalendarKind. gregorian) {} public I Nt Month {get; private set;} public int Day {get; private set;} public CalendarKind Calendar {get; private set;} public static bool operator = (MonthDayDate d1, monthDayDate d2) {return d1.Month = d2.Month & d1.Day = d2.Day & d1.Calendar = d2.Calendar;} public static bool operator! = (MonthDayDate d1, MonthDayDate d2) {return! (D1 = d2) ;}} public enum CalendarKind {// Gregorian calendar (Gregorian calendar) Gregorian, // Chinese lunar calendar (lunar calendar) LunarCalendar }}
Note: In the Model, we added the business logic. For example, the ToDateTimeRange method of Holiday is dependent on the Conversion logic from the external lunar calendar to the Gregorian calendar, and the external logic is used here, is it a poor design? So it is necessary for me to declare that this code is a semi-experimental code, not a production code. Since some external method logic is dependent here, I also list this part of code (DateUtility. cs ):
Using System; using System. collections. generic; using System. globalization; using System. linq; using System. text; using System. threading. tasks; namespace HelloBaby {public class DateUtility {// <summary> // obtain the time period enumeration // </summary> public static IEnumerable <DateTime> RangeDay (
DateTime starting, DateTime ending) {for (DateTime d = starting; d <= ending; d = d. addDays (1) {yield return d ;}/// <summary> // convert the lunar calendar to the Gregorian calendar /// </summary> public static DateTime ConvertLunarYearDate (int year, int month, int day) {ChineseLunisolarCalendar calendar = new ChineseLunisolarCalendar (); return calendar. toDateTime (year, month, day, 0, 0, 0, 0 );}}}
Business
The program has completed more than half of this writing, followed by some judgment rule logic. Here we use the extension method (DateExtensions. cs ):
Using System; using System. collections. generic; using System. globalization; using System. linq; using System. text; using System. threading. tasks; namespace HelloBaby {public static class DateExtensions {// <summary> // determine whether the date is a holiday, use the default holiday rule /// </summary> public static bool IsHoliday (this DateTime date) {return date. isHoliday (defaulthoocs. holidays) ;}/// <summary> /// determines whether the date is a holiday. Use the specified holiday rule /// </summary> public static bool IsHoliday (
This DateTime date, IEnumerable <Holiday> holidays) {return holidays. Any (d => d. ToDateTimeRange (date. Year). Contains (date ));}}}
Tip: in the practice of the project, we try to follow the TDD development mode, especially for the code at the business processing layer. The unit test code is not pasted here and omitted.
Application
Now our fields and business rules have been completed, and we can start our application. In a data-centric age, with data, we can make full use of our imagination, here, I simply go back to the original problem point, because although I took this opportunity to practice writing code by hand, I had to help my wife solve the problem, therefore, my application scenario is to calculate the national statutory holidays included in the 98-day maternity leave. I mainly use the LINQ query here:
Internal static void PrintSolutions (int days) {var sample = DateUtility. rangeDay (new DateTime (2014, 1, 1), new DateTime (2015, 12, 31); var holidayCollection = defaulthoocs. holidays; var solutions = from begin sample from end in sample let range = DateUtility. rangeDay (begin, end) where range. count () = days select new {Begin = begin, End = end, HolidayCount = range. count (d => d. isHoliday ()) }; // Explicitly queries a set to avoid multiple queries. // typical scenario of changing the space time !!! Var local = solutions. toList (); var groups = from all in local group all by all. holidayCount into g select new {Holidays = g. key, SolutionCount = g. count ()}; var best = from all in local where all. holidayCount = 0 select all; Console. writeLine ("group results:"); foreach (var group in groups) {Console. writeLine ("{0} solutions for {1} holidays", group. solutionCount, group. holidays);} Console. writeLine (); Console. writeLine ("best results:"); foreach (var one in best) {Console. writeLine ("from {0: yyyy-MM-dd} to {1: yyyy-MM-dd}", one. begin, one. end );}}
When I was chatting with my wife, I agreed with her preliminary plan, because the 98-day holiday will only cross the New Year's Day holiday, I don't think there will be any more than a statutory holiday during my 98-day holiday. Even if there is one, this kind of solution is rare. Although I have comforted my wife, I still patiently did the test, I used the time sample from the beginning of 2014 to the end of 2015. The test results showed that there could not be 98 days without a statutory holiday. I found that there was such a period of time in 2015, 98 days without passing through a statutory holiday, it is calculated as: to 2015-09-26. Oh, my wife, you have no fun.
Conclusion
Although some of the wording in the article is to solve the problem, to tell the truth, the ultimate goal is to train your hands, and you are relatively lazy, just watching things and do not love your hands, but still feel that you must have an open mind. I still have some questions about the query of LINQ, that is, the performance of the query execution behind it? It is like writing an SQL statement. The same query has different writing methods and different writing methods have different performance considerations. Therefore, we generally try to follow the rules to write a query, then, how does LINQ to Object standardize all this? In the future, other commonly used query providers (such as LINQ to Entity, although I have carefully read some books and cases, I still feel that I have not understood them), it seems that I can explore them again when I have time, you are welcome to share your thoughts! Hope you can meet people of insight!
Finally, let's talk about it again: the paternity leave for Mao Shanghai is only for three days in the district, and it is still aimed at late childbearing. Compared with the policies of other provinces and cities, it is too unfriendly !!!
In the C language, what is the symbol (->) and how to use it?
This is a symbol in the struct pointer. Write a program to explain it, for example:
# Include <stdio. h>
Struct STU // define a struct
{
Int num;
} Stu;
Int main ()
{
Struct STU * p; // defines a struct pointer.
P = stu; // p points to the struct variable stu.
Stu. num = 100; // attaches an initial value to the struct member num.
Printf ("% d", p-> num); // output the num value in stu
Return;
}
As you can see, the-> method is to reference the variable in the struct !!
Format: p-> struct member (such as p-> num)
The function is equivalent to stu. num or (* p). num.
I don't know. You don't understand, and don't understand call me. O (∩ _ ∩) O ~
Hope to adopt it.
In the C language, what is the symbol (->) and how to use it?
This is a symbol in the struct pointer. Write a program to explain it, for example:
# Include <stdio. h>
Struct STU // define a struct
{
Int num;
} Stu;
Int main ()
{
Struct STU * p; // defines a struct pointer.
P = stu; // p points to the struct variable stu.
Stu. num = 100; // attaches an initial value to the struct member num.
Printf ("% d", p-> num); // output the num value in stu
Return;
}
As you can see, the-> method is to reference the variable in the struct !!
Format: p-> struct member (such as p-> num)
The function is equivalent to stu. num or (* p). num.
I don't know. You don't understand, and don't understand call me. O (∩ _ ∩) O ~
Hope to adopt it.