Converting country codes in .NET

前端 未结 10 1679
难免孤独
难免孤独 2020-12-04 23:55

In .NET is there any way to convert from three letter country codes (defined in ISO 3166-1 alpha-3) to two letter language codes (defined in ISO 3166-1 alpha-2) eg. convert

10条回答
  •  遥遥无期
    2020-12-05 00:51

    UPDATED:

    Didn't read the question properly before. The following should now be correctly converting from ISO 3166-1 alpha-3 to ISO 3166-1 alpha-2:


    There's no built in way of doing it. You'll need to iterate through the CultureInfos to get the RegionInfos in order to manually find the match (this is pretty ineffecient so some caching would be advisable):

    public string ConvertThreeLetterNameToTwoLetterName(string name)
    {
        if (name.Length != 3)
        {
            throw new ArgumentException("name must be three letters.");
        }
    
        name = name.ToUpper();
    
        CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures);
        foreach (CultureInfo culture in cultures)
        {
            RegionInfo region = new RegionInfo(culture.LCID);
            if (region.ThreeLetterISORegionName.ToUpper() == name)
            {
                return region.TwoLetterISORegionName;
            }
        }
    
        return null;
    }
    

提交回复
热议问题