Write code to write code

Hello,
For my site I am making a asp.net subdomain that needs the users country. The service returns the country in a 2 letter code but I need to store the “long name” in the database so I will do a switch statement. Being a bit lazy I don’t want to write 253 cases in switch statement. Does anyone have a idea on how I can create a quick program to write the 253 switch statements?

Thanks,

A sample of the list:

A1,“Anonymous Proxy”
A2,“Satellite Provider”
O1,“Other Country”
CA,“Canada”
US,“United States”

If you have it in database, you can just query it every time. Or you can have a static dictionary with two letter part being a key and the long string being the value of the dictionary item.

Thanks,
Just curious if there is any way to make code that writes code for this example.

Do you want this code to be run once to generate final code? Or is it something that will have to be generated during runtime?

Just once.
Actutally the dictionary would work but I just want to do a preformance test.

Ok, then you can write small program that will read every pair from db and output it into debug window or console and then just copy the whole text from the output.

Something like this:


System.Diagnostics.Debug.WriteLine("static Dictionary<string, string> _country = new Dictionary<string, string>() {");

while( /*more records in db*/ )
{
     //read a record into two string variables
     //recordKey
     //recordValue
     //Output new entry for dictionary
     System.Diagnostics.Debug.WriteLine(string.Format("{ \"{0}\", \"{1}\" },",recordKey,recordValue));
}

System.Diagnostics.Debug.WriteLine("};");

you should end up with something like this:


static Dictionary<string, string> _country = new Dictionary<string, string>()
        {
            {"US", "United States" },
            {"CA", "Canada" }
        };

Thanks Again

You are welcome!

I use SQL queries to do this quite often as well.

Your SQL query would be something like

select " case “”" + shortName + “”": longname = “”" + longname “”"; break;" as ‘switchline’ from yourtable order by shortname

you would then just paste that into your switch block.

Depends if you’re a SQL junkie or a code junkie (or an Excel Monkey as I end up using all the time to do this as well) as to which one you use to do this.

1 Like

Xzibit approves this topic.

1 Like

Do you have any idea on how to convert this "A2,“Satellite Provider” to two different strings.
Thanks,

Using Split method and comma as separator.

Thanks Agains,
Just making a program to autowrite the code.

It takes 00:00:00.001170 seconds to find the the 252 value in the switch statement. Do you know how to make a look with the dictionary.
Thanks,

if( _dictionary.ContainsKey(key) )
{
    string strValue = _dictionary[key];
}