RKNirvana
RKNirvana

Reputation: 75

Populate country list with respective two letter and three letter code in c#

Can any one please help in populating the list of country names, its respective two letter code and three letter codes.. I tried the below snippet, but its giving me incomplete results.

 static void Main(string[] args)
    {
        List<string> list = new List<string>();
        foreach (CultureInfo ci in CultureInfo.GetCultures(CultureTypes.AllCultures & ~CultureTypes.NeutralCultures))
        {
            try
            {
                RegionInfo myRI1 = new RegionInfo(ci.LCID);
                list.Add(String.Format("{0,-12}{1,-12}{2}", myRI1.TwoLetterISORegionName, myRI1.EnglishName, myRI1.ThreeLetterISORegionName));
            }
            catch { }
       }

    list.Sort();  // sort by name
        // write to console
    foreach (string str in list)
        Console.WriteLine(str);

    Console.WriteLine("Total Countries" + list.Count.ToString());
    Console.ReadKey();
    }
}

Upvotes: 0

Views: 1899

Answers (1)

Magnus Grindal Bakken
Magnus Grindal Bakken

Reputation: 2113

If you really must retrieve this information using C#, this is how I'd do it:

var regions = CultureInfo.GetCultures(CultureTypes.AllCultures)
    .Where(c => !c.IsNeutralCulture && c.LCID != 0x7f)
    .Select(c => new RegionInfo(c.LCID))
    .GroupBy(r => r.TwoLetterISORegionName) // This is an alternative to using Distinct
    .Select(g => g.First())                 // It's probably not very efficient, but the list is so small anyway.
    .OrderBy(r => r.TwoLetterISORegionName)
    .ToList();

(The culture with the LCID 0x7f is the InvariantCulture, which doesn't have an associated RegionInfo.)

This gives only 127 countries on my computer. Your method gives a lot more results because there are many instances of multiple CultureInfos that share the same RegionInfo. For instance, there are four different CultureInfos that point to the RegionInfo for Spain: ca-ES (Catalan), eu-ES (Basque), gl-ES (Galician) and es-ES (Spanish). This is because CultureInfo is primarily concerned with languages, and languages and regions don't need to match up.

There are way more than 127 countries in the world. The problem is that approaching this by using CultureInfo and RegionInfo can only ever tell you about the countries that your computer happens to know about, which is unlikely to be a complete list. What's more, as the name RegionInfo suggests, they aren't necessarily even countries or nations. For example, one of the RegionInfo entries on my computer is "Caribbean", with a TwoLetterISORegionName of 029 (which I have to admit is rather strange). The Caribbean is clearly not a country.

A better way to solve your problem is to look up a list of countries elsewhere, like, say, here and store them in a table somewhere in your program.

Upvotes: 2

Related Questions