Getting CultureInfo from RegionInfo.TwoLetterISORegionName

940 views Asked by At

In db I already have stored values with RegionInfo.TwoLetterISORegionName values. Atm I have values like 'be' for Belgium, 'no', 'gb', 'en' etc.

If I write:

var culture = new CultureInfo("be");

instead of Belgium, I get Belarus.

So I need a way to get CultureInfo from RegionInfo.TwoLetterISORegionName.

1

There are 1 answers

0
xanatos On

Given a two letter region name, there are multiple cultures that can be associated with that region name (because in a country multiple languages can be spoken). For example for Switzerland there are 4 cultures: de, fr, it, rm.

And now some code:

public static ILookup<string, CultureInfo> RegionToCultures()
{
    // All the local cultures
    CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures);

    // We "group" the cultures by their TwoLetterISORegionName
    return cultures.ToLookup(x => new RegionInfo(x.LCID).TwoLetterISORegionName);
}

The code returns a ILookup<string, CultureInfo> (consider it to be a IDictionary<string, IEnumerable<CultureInfo>>).

Use it like:

var rtoc = RegionToCultures();

and then:

var switzerlandCultures = rtoc["CH"];

foreach (CultureInfo culture in switzerlandCultures)
{
    Console.WriteLine(culture.EnglishName);
}

Note that a ILookup<,> won't throw an exception if used with a non-existing key: rtoc["aaaaa"] will simply return an empty IEnumerable<>.