Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# data structure to get months

I’ve got a (month of a) date written as e.g. ‘MARS’ which would need to return 03 (as it is the 3rd month).

Below are all my options for each month (3 languages):

{ "JAN", };
{ "FEV", "FEB", };
{ "MARS", "MAAR", "MÄR" };
{ "AVR", "APR" };
{ "MAI", "MEI" };
{ "JUIN", "JUN" };
{ "JUIL", "JUL" };
{ "AOUT", "AUG" };
{ "SEPT", "SEP" };
{ "OCT", "OKT" };
{ "NOV", };
{ "DEC", "DEZ" };

Unfortunately the C# DateTime parser doesn’t recognize e.g. "MAAR" (it does recognize "MARS") so I guess I’d have to write something myself.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What is the proper way to data structure this? I was thinking of a jagged array or a list within list.

With a jagged array:

        string[][] jagged_array = new string[12][];
        jagged_array[0] = new string[1];
        jagged_array[0][0] = "01";
        jagged_array[0][1] = "JAN";
        jagged_array[1] = new string[2];
        jagged_array[1][0] = "02";
        jagged_array[1][1] = "FEV";
        jagged_array[1][2] = "FEB";
        jagged_array[2] = new string[3];
        jagged_array[2][0] = "03";
        jagged_array[2][1] = "MARS";
        jagged_array[2][2] = "MAAR";
        jagged_array[2][3] = "MÄR";
        jagged_array[3] = new string[2];
        jagged_array[3][0] = "04";
        jagged_array[3][1] = "AVR";
        jagged_array[3][2] = "APR";
        jagged_array[4] = new string[2];
        jagged_array[4][0] = "05";
        jagged_array[4][1] = "MAI";
        jagged_array[4][2] = "MEI";
        (...)

Is this the recommended way of structuring the data?
How do I access the month number (well, month string, which can be casted to number)?

Something like get_month("MAAR") –> should return "03". Is there an easy way to get this or do I need to loop over the individual items?

>Solution :

A simple Dictionary can do the job

int GetMonthFromString(string str)
{
    var monthNames = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
    monthNames.Add("JAN", 1);

    monthNames.Add("FEB", 2);
    monthNames.Add("FEV", 2);
....
    if (!monthNames.ContainsKey(str))
        throw new ApplicationExcepion("invalid string for month"); //handle somehow an invalid string

    return monthNames[str];

}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading