From 4df1cc62d8e61f250b2bd8ee5cdceaee9eb7b130 Mon Sep 17 00:00:00 2001 From: nikola-golijanin Date: Tue, 3 Dec 2024 12:22:10 +0100 Subject: [PATCH] Optimize country lookup by using a dictionary for faster access and improve null handling in country retrieval methods --- src/CountryData.Standard/CountryHelper.cs | 28 +++++++++++++++-------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/src/CountryData.Standard/CountryHelper.cs b/src/CountryData.Standard/CountryHelper.cs index 6dcb817..f1bc02c 100644 --- a/src/CountryData.Standard/CountryHelper.cs +++ b/src/CountryData.Standard/CountryHelper.cs @@ -11,6 +11,7 @@ public class CountryHelper { private readonly IEnumerable _Countries; private const string strFileName = "CountryData.Standard.data.json"; + private readonly Dictionary _countriesByShortCode; public CountryHelper() { @@ -20,6 +21,7 @@ public CountryHelper() { country.CountryFlag = GetCountryEmojiFlag(country.CountryShortCode); } + _countriesByShortCode = _Countries.ToDictionary(c => c.CountryShortCode); } @@ -58,9 +60,12 @@ public virtual IEnumerable GetCountryData() /// /// /// Country + /// Thrown when the shortCode parameter is null. + public Country GetCountryByCode(string shortCode) { - return _Countries.SingleOrDefault(c => c.CountryShortCode == shortCode); + _countriesByShortCode.TryGetValue(shortCode, out var country); + return country; } /// @@ -75,15 +80,18 @@ public string GetCountryEmojiFlag(string shortCode) /// - /// Selects Regions in a Particular Country + /// Selects Regions in a Particular Country, if the country is not found, it returns an empty list /// /// /// List a list of regions + /// Thrown when the shortCode parameter is null. public List GetRegionByCountryCode(string ShortCode) { - return _Countries.Where(x => x.CountryShortCode == ShortCode) - .Select(r => r.Regions).FirstOrDefault() - .ToList(); + _countriesByShortCode.TryGetValue(ShortCode, out var country); + + return country is null + ? Enumerable.Empty().ToList() + : country.Regions.ToList(); } /// @@ -100,9 +108,11 @@ public List GetRegionByCountryCode(string ShortCode) /// /// /// string + /// Thrown when the shortCode parameter is null. + public string GetPhoneCodeByCountryShortCode(string shortCode) { - var country = _Countries.SingleOrDefault(c => c.CountryShortCode == shortCode); + _countriesByShortCode.TryGetValue(shortCode, out var country); return country?.PhoneCode; } @@ -125,11 +135,11 @@ public IEnumerable GetCountryByPhoneCode(string phoneCode) /// /// The short code of the country. /// An IEnumerable of Currency objects associated with the specified country. + /// Thrown when the shortCode parameter is null. public IEnumerable GetCurrencyCodesByCountryCode(string shortCode) { - return _Countries.Where(x => x.CountryShortCode == shortCode) - .SelectMany(c => c.Currency) - .ToList(); + _countriesByShortCode.TryGetValue(shortCode, out var country); + return country?.Currency.ToList(); }