2014-12-24 180 views
4

我知道如何將ISO 3166-2代碼轉換爲完整的英文名稱,例如通過使用RegionInfo將「美國」改爲「美國」。國家名稱爲ISO 3166-2代碼

但是,我該如何做相反的事情,即需要「美國」並返回「美國」?

+0

很高興看到人們是有幫助的,但得到(基本上)相同的答案四次是相當必要的。聖誕節快樂! – Onots

回答

10
//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); 
1

主要思想:取所有區域對象,並從中選擇一個包含給定全名的區域對象。

var regionFullNames = CultureInfo 
         .GetCultures(CultureTypes.SpecificCultures) 
         .Select(x => new RegionInfo(x.LCID)) 
         ; 
var twoLetterName = regionFullNames.FirstOrDefault(
         region => region.EnglishName.Contains("United States") 
        ); 
1
 /// <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; 
     } 
1

你可能只是做這樣的事情:

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 ; 
    } 

} 
相關問題