Skip to content

Instantly share code, notes, and snippets.

@cajuncoding
Last active May 21, 2024 20:17
Show Gist options
  • Save cajuncoding/69422463cf74f8162ec25d9149ce91a8 to your computer and use it in GitHub Desktop.
Save cajuncoding/69422463cf74f8162ec25d9149ce91a8 to your computer and use it in GitHub Desktop.
Simple helper to find and convert RegionInfo details using two or three letter Country Codes
using System;
using System.Globalization;
using System.Linq;
namespace CajunCoding
{
/// <summary>
/// Simple helper to find and convert RegionInfo details using two or three letter Country Codes.
/// NOTE: Inspired but fully rewritten from the Gist: https://gist.github.com/BenjaminAdams/277928c7ad291ea7aea8
/// </summary>
public static class RegionInfoFinder
{
public static class RegionInfoFinder
{
private static readonly ILookup<string, RegionInfo> RegionInfoLookupByThreeLetterCountryCode = CultureInfo
.GetCultures(CultureTypes.SpecificCultures)
.Select(c => new RegionInfo(c.Name))
.ToLookup(ri => ri.ThreeLetterISORegionName, StringComparer.OrdinalIgnoreCase);
private static readonly ILookup<string, RegionInfo> RegionInfoLookupByTwoLetterCountryCode = CultureInfo
.GetCultures(CultureTypes.SpecificCultures)
.Select(c => new RegionInfo(c.Name))
.ToLookup(ri => ri.TwoLetterISORegionName, StringComparer.OrdinalIgnoreCase);
public static RegionInfo? FromThreeLetterCountryCode(string threeLetterCountryCode)
=> RegionInfoLookupByThreeLetterCountryCode[threeLetterCountryCode].FirstOrDefault();
public static RegionInfo? FromTwoLetterCountryCode(string twoLetterCountryCode)
=> RegionInfoLookupByTwoLetterCountryCode[twoLetterCountryCode].FirstOrDefault();
}
}
}
@cajuncoding
Copy link
Author

Inspired by the original gist here: https://gist.github.com/BenjaminAdams/277928c7ad291ea7aea8 but incorporates the fix noted in one of the comments and streamlines the logic with Linq and faster lookup caching...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment