Converting country codes in .NET

前端 未结 10 1703
难免孤独
难免孤独 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:47

    Some of the above answers are O(N) for lookups, which is fine if you're only doing it once, but generally you'll want to call this more than once per process in which case you'll probably want something more efficient.

    var Iso3ToIso2Mapping = CultureInfo.GetCultures(CultureTypes.SpecificCultures)
      .Select(ci => new RegionInfo(ci.LCID))
      .GroupBy(ri => ri.ThreeLetterISORegionName)
      .ToDictionary(g => g.Key, g => g.First().TwoLetterISORegionName);
    

    Then you can just do a lookup with:

    var iso2CountryCode = Iso3ToIso2Mapping["AUS"];
    Console.WriteLine(iso2CountryCode);
    

    Prints:

    AU
    

提交回复
热议问题