Last active
May 21, 2024 20:17
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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...