Search code examples
c#globalization

C# get RegionInfo, TwoLetterISORegionName, by Swedish country name


I need to get the two letter ISO region name, ISO 3166 - ISO 3166-1 alpha 2, for countries. My problem is that I only have the country names in Swedish, for example Sverige for Sweden and Tyskland for Germany. Is it possible to get RegionInfo from only this information? I know it is possible for English country names.

Works:

var countryName = "Sweden";
//var countryName = "Denmark";
var regions = CultureInfo.GetCultures(CultureTypes.SpecificCultures).Select(x => new RegionInfo(x.LCID));
var englishRegion = regions.FirstOrDefault(region => region.EnglishName.Contains(countryName));
var twoLetterISORegionName = englishRegion.TwoLetterISORegionName;

https://stackoverflow.com/a/14262292/3850405


Solution

  • Try comparing with NativeName:

    string nativeName = "Sverige"; // Sweden
    
    var region = CultureInfo
        .GetCultures(CultureTypes.SpecificCultures)
        .Select(ci => new RegionInfo(ci.LCID))
        .FirstOrDefault(rg => rg.NativeName == nativeName);
    
    Console.Write($"{region.TwoLetterISORegionName}");
    

    Edit: It seems that we actually want to find out RegionInfo instance by its Swedish name

      Sverige  -> Sweden
      Tyskland -> Germany
      ...
    

    In this case we should use DisplayName instead of NativeName:

    string swedishName = "Sverige"; // Sweden
    
    var region = CultureInfo
        .GetCultures(CultureTypes.SpecificCultures)
        .Select(ci => new RegionInfo(ci.LCID))
        .FirstOrDefault(rg => rg.DisplayName == swedishName);
    

    and we should be sure that we use localized .Net

    The DisplayName property displays the country/region name in the language of the localized version of .NET Framework. For example, the DisplayName property displays the country/region in English on the English version of the .NET Framework, and in Spanish on the Spanish version of the .NET Framework.