I receive a string as a json parameter and it's supposed to be a timezone ID. I want to check for that.
This is what I have:
TheTimezoneID = TheTimezoneID.Trim();
var AllTimezones = TimeZoneInfo.GetSystemTimeZones();
if (TheTimezoneID "is a valid .net timezone" == true) {}
What's the linq expression that'll test if TheTimezoneID
is in AllTimezones
? I tried using .Any
but it's not working.
Thanks.
If you're going to do this in various situations you should probably use:
private static readonly HashSet<string> AllTimeZoneIds =
new HashSet<string>(TimeZoneInfo.GetSystemTimeZones()
.Select(tz => tz.Id));
Then you can just use:
if (AllTimeZoneIds.Contains(timeZoneId))
There's no need to use LINQ to iterate over the whole time zone list on each time when a hash set can just perform an O(1) lookup.
If you're just curious about using Any
, it would be:
if (AllTimeZoneIds.Select(tz => tz.Id).Contains(timeZoneid))
or
if (AllTimeZoneIds.Any(tz => tz.Id == timeZoneid))
Note that "time zone ID" is a pretty woolly concept. This will check if it's a valid .NET time zone ID. If you're actually getting time zones like "Europe/London", that's a different matter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With