Using LINQ to replace foreach
October 18, 2011 Leave a comment
I sometimes forget how powerful LINQ can be – especially when dealing with older constructs that work fine. I recently wrote this nugget of crappy code:
Unit unit = null; foreach (Hex hex in Game.CurrentBoard) { if (hex.CurrentUnit != null) { if (hex.CurrentUnit.Country.AlliesIndicator == true) { unit = hex.CurrentUnit; } } }
I looked at it for a second and then re-wrote it using LINQ:
var q = (from h in Game.CurrentBoard where h.CurrentUnit.Country.AlliesIndicator == true select h);
Take about an improvement in readability!