Another quick one! Forcing myself to learn LINQ, so I decided to rewrite some looping code. The original code; simple enough, loop thru all the daylight adjustments for a timezone and build a list of date/time and offset.
List<TransitionOffset> transitions = new List<TransitionOffset>(); foreach (TimeZoneInfo.AdjustmentRule adj in TimeZoneInfo.FindSystemTimeZoneById("AUS Eastern Standard Time").GetAdjustmentRules()) { if (adj.DateEnd.Year >= 2010) { for (int year = 2010; year <= 2015; year++) { transitions.Add(new TransitionOffset { Transition = GetDateTime(year, adj.DaylightTransitionStart), Offset = adj.DaylightDelta.TotalHours }); transitions.Add(new TransitionOffset { Transition = GetDateTime(year, adj.DaylightTransitionEnd), Offset = 0 }); } } } transitions = transitions.OrderBy(t => t.Transition).ToList();
..and again in LINQ
var zoneAdjs = from adj in TimeZoneInfo.FindSystemTimeZoneById("AUS Eastern Standard Time").GetAdjustmentRules() where adj.DateEnd.Year >= 2010 from year in Enumerable.Range(2010, 6) let trans = new[] { new { Transition = GetDateTime(year, adj.DaylightTransitionEnd), Offset = 0.0}, new { Transition = GetDateTime(year, adj.DaylightTransitionStart), Offset = adj.DaylightDelta.TotalHours} } from tran in trans orderby tran.Transition select tran;
Any more readable / maintainable than the non-LINQ version? It definitely took longer to write while I’m a LINQ “newbie”. The most complicated bit was pulling the DaylightTransitionEnd and DaylightTransitionStart into one collection. This collection is only ever used to create JSON, so I like being able to serialize anonymous types from LINQ, and skip creating classes that are only used to serialize.
Post a Comment