How to get country name
Well, this regular expression seems to do the job in most cases:
var regex = new System.Text.RegularExpressions.Regex(@"([\w+\s*\.*]+\))");
foreach (var item in CultureInfo.GetCultures(CultureTypes.SpecificCultures))
{
var match = regex.Match(item.DisplayName);
string countryName = match.Value.Length == 0 ? "NA" : match.Value.Substring(0, match.Value.Length - 1);
Console.WriteLine(countryName);
}
You can use the Name property of the CultureInfo to construct a RegionInfo. You can then use the DisplayName property. Try:
foreach (CultureInfo ci in CultureInfo.GetCultures(CultureTypes.SpecificCultures))
{
var ri = new RegionInfo(ci.Name);
Console.WriteLine(ri.DisplayName);
}
// Build your normal dictionary as container
Dictionary<string, string> countryNames = new Dictionary<string, string>();
foreach (CultureInfo ci in CultureInfo.GetCultures(CultureTypes.SpecificCultures))
{
RegionInfo ri = new RegionInfo(ci.Name);
// Check if the ISO language code is already in your collection
// Because you don't want double entries in a country box because we had to use the culture info
if (!countryNames.ContainsKey(ri.TwoLetterISORegionName))
{
countryNames.Add(ri.TwoLetterISORegionName.ToUpper(), ri.EnglishName);
}
}
// Code for dictionary to dropdownlist transform can be written with your personal preference for symantics
SelectList countryDropdown = new SelectList(countryNames.OrderBy(o => o.Value), "Key", "Value");
Or ready for use without comments:
Dictionary<string, string> countryNames = new Dictionary<string, string>();
foreach (CultureInfo ci in CultureInfo.GetCultures(CultureTypes.SpecificCultures))
{
RegionInfo ri = new RegionInfo(ci.Name);
if (!countryNames.ContainsKey(ri.TwoLetterISORegionName)) countryNames.Add(ri.TwoLetterISORegionName.ToUpper(), ri.EnglishName);
}
SelectList countryDropdown = new SelectList(countryNames.OrderBy(o => o.Value), "Key", "Value");