Reputation: 46750
I have a country name like Australia and I would like to get the ISO 3166-1 alpha 2 code like AU in this case. Is there a way to easily do this in .NET?
Upvotes: 1
Views: 4891
Reputation: 1187
Similar question asked in Country name to ISO 3166-2 code
/// <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;
}
Upvotes: 4
Reputation: 17541
You can get a JSON mapping of country codes to names from http://country.io/names.json. You'd just need to flip this with something like:
var countries = codes.ToDictionary(x => x.Value, x => x.Key);
And then you could easily get the country code from the new dictionary.
Upvotes: 0
Reputation: 499002
There is nothing built in to convert a country name to its 2 alpha ISO code.
You can create a dictionary to map between the two.
var countryToISO2Map = new Dictionary<string,string>{
{"Australia", "AU"},
...
};
Upvotes: 2