我知道如何将 ISO 3166-2 代码转换为全英文名称,例如使用RegionInfo
.
但是,我该如何做相反的事情,即接受“美国”并返回“美国”?
我知道如何将 ISO 3166-2 代码转换为全英文名称,例如使用RegionInfo
.
但是,我该如何做相反的事情,即接受“美国”并返回“美国”?
//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);
主要思想:获取所有区域对象并从中选择一个包含给定全名的对象。
var regionFullNames = CultureInfo
.GetCultures( CultureTypes.SpecificCultures )
.Select( x => new RegionInfo(x.LCID) )
;
var twoLetterName = regionFullNames.FirstOrDefault(
region => region.EnglishName.Contains("United States")
);
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 ;
}
}
/// <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;
}