字符串是.Net中的有效时区

fre*_*hie 4 c# timezone

我收到一个字符串作为json参数,它应该是一个时区ID.我想检查一下.

这就是我所拥有的:

TheTimezoneID = TheTimezoneID.Trim();
var AllTimezones = TimeZoneInfo.GetSystemTimeZones();

if (TheTimezoneID "is a valid .net timezone" == true) {}
Run Code Online (Sandbox Code Playgroud)

什么是linq表达式,将测试是否TheTimezoneIDAllTimezones?我尝试过使用.Any但它不起作用.

谢谢.

Jon*_*eet 9

如果您打算在各种情况下执行此操作,您应该使用:

private static readonly HashSet<string> AllTimeZoneIds = 
    new HashSet<string>(TimeZoneInfo.GetSystemTimeZones()
                                    .Select(tz => tz.Id));
Run Code Online (Sandbox Code Playgroud)

然后你可以使用:

if (AllTimeZoneIds.Contains(timeZoneId))
Run Code Online (Sandbox Code Playgroud)

当哈希集只能执行O(1)查找时,不需要使用LINQ迭代整个时区列表.

如果你只是对使用感到好奇Any,那就是:

if (AllTimeZoneIds.Select(tz => tz.Id).Contains(timeZoneid))
Run Code Online (Sandbox Code Playgroud)

要么

if (AllTimeZoneIds.Any(tz => tz.Id == timeZoneid))
Run Code Online (Sandbox Code Playgroud)

请注意,"时区ID"是一个非常羊毛的概念.这将检查它是否是有效的.NET时区ID.如果你真的得到像"欧洲/伦敦"这样的时区,那就不一样了.