Country name to ISO 3166-2 code
Asked Answered
R

4

8

I know how to convert an ISO 3166-2 code to the full English name, e.g. "US" to "United States" by using RegionInfo.

However, how can I do the opposite, i.e. that takes "United States" and returns "US"?

Repressive answered 24/12, 2014 at 0:13 Comment(1)
Nice to see people being helpful, but getting (basically) the same answer four times is rather unnecessary. Merry Christmas!Thoron
T
13
//Get the cultureinfo
RegionInfo rInfo = new RegionInfo("us");
string s = rInfo.EnglishName;

//Convert it back
CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures);
 CultureInfo cInfo = cultures.FirstOrDefault(culture => new RegionInfo(culture.LCID).EnglishName == s);
Timeous answered 24/12, 2014 at 0:30 Comment(0)
B
4

The main idea: take all region objects and select from them one which contains given full name.

var regionFullNames = CultureInfo
                      .GetCultures( CultureTypes.SpecificCultures )
                      .Select( x => new RegionInfo(x.LCID) )
                      ;
var twoLetterName = regionFullNames.FirstOrDefault(
                       region => region.EnglishName.Contains("United States")
                    );
Burn answered 24/12, 2014 at 0:20 Comment(0)
T
2

You could just do something like this:

class CountryCodeMap
{
  private static Dictionary<string,string> map =
    CultureInfo
    .GetCultures(CultureTypes.AllCultures)
    .Where( ci => ci.ThreeLetterISOLanguageName != "ivl" )
    .Where( ci => !ci.IsNeutralCulture )
    .Select( ci => new RegionInfo(ci.LCID) )
    .Distinct()
    .ToDictionary( r => r.Name , r => r.EnglishName )
    ;

  public static string GetCountryName( string isoCountryCode )
  {
    string countryName ;
    bool found = map.TryGetValue( isoCountryCode, out countryName ) ;

    if ( !found ) throw new ArgumentOutOfRangeException("isoCountryCode") ;

    return countryName ;
  }

}
Turnover answered 24/12, 2014 at 1:45 Comment(0)
T
1
        /// <summary>
        /// English Name for country
        /// </summary>
        /// <param name="countryEnglishName"></param>
        /// <returns>
        /// Returns: RegionInfo object for successful find.
        /// Returns: Null if object is not found.
        /// </returns>
        static RegionInfo getRegionInfo (string countryEnglishName)
        {
            //Note: This is computed every time. This may be optimized
            var regionInfos = CultureInfo.GetCultures(CultureTypes.SpecificCultures)
               .Select(c => new RegionInfo(c.LCID))
               .Distinct()
               .ToList();
             RegionInfo r = regionInfos.Find(
                    region => region.EnglishName.ToLower().Equals(countryEnglishName.ToLower()));                       
             return r;
        }
Tarsus answered 24/12, 2014 at 0:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.