How to check exists culture in .NET

前端 未结 4 1754
生来不讨喜
生来不讨喜 2021-01-17 08:39

I have this code, when I try to get not existed culture I get exception.
Is there exists method like TryGetCultureInfo, which return bool val

4条回答
  •  太阳男子
    2021-01-17 09:26

    If you want it to be fast you can use:

    internal static class Culture
    {
        private static readonly HashSet CultureNames = CreateCultureNames();
    
        internal static bool Exists(string name)
        {
            return CultureNames.Contains(name);
        }
    
        private static HashSet CreateCultureNames()
        {
            var cultureInfos = CultureInfo.GetCultures(CultureTypes.AllCultures)
                                          .Where(x => !string.IsNullOrEmpty(x.Name))
                                          .ToArray();
            var allNames = new HashSet(StringComparer.OrdinalIgnoreCase);
            allNames.UnionWith(cultureInfos.Select(x => x.TwoLetterISOLanguageName));
            allNames.UnionWith(cultureInfos.Select(x => x.Name));
            return allNames;
        }
    }
    

提交回复
热议问题